#To define a particular parameter, replace the 'parameterName' inside itsm.getParameter('parameterName') with that parameter's name
hours=itsm.getParameter('hours')#1200"
import os
from subprocess import PIPE,Popen
import time
import datetime
import ctypes
import sys
import re


drive=map(lambda x:x.strip(),os.popen("wmic logicaldisk get name").read().split()[1:])

def alert(arg):
    return sys.stderr.write("%d%d%d" % (arg, arg, arg))
class disable_file_system_redirection:
    _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
    _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
    def __enter__(self):
        self.old_value = ctypes.c_long()
        self.success = self._disable(ctypes.byref(self.old_value))
    def __exit__(self, type, value, traceback):
        if self.success:
            self._revert(self.old_value)
def cmd_runner(cmd):
    with disable_file_system_redirection():
        obj=Popen(cmd,stdout=PIPE,stderr=PIPE,shell=True)
        res,err=obj.communicate()
        if err:
            return err
        else:
            return res

hn=os.popen("hostname").read().split()[0]
n=os.popen("wmic os get systemdrive /Value").read().split()[0]
cmd1='powershell "Set-ExecutionPolicy RemoteSigned"'
cmd_runner(cmd1)

ls=['disk']
r=[]
for i in ls:
    cmd2="""powershell.exe "Get-EventLog -LogName System -EntryType Error -Source '%s' -Newest 1 -After (Get-Date).Addhours(-%s)| format-table -wrap "
"""%(i,hours)
    r.append(cmd_runner(cmd2))
#print r
l=[]
for i in r:
    if "No matches found" in i:
        l.append((0,i))#alert(0)
    elif i=='':
        l.append((0,i))#alert(0)
    else:
        l.append((1,i))#alert(1)
ones=[]
for i in l:
    if i[0]==1:
        ones.append((i[0],i[1]))
if ones==[]:
    alert(0)
else:
    k=[]
    for i in ones:
        #print i[1]
        k.append((re.findall("\Harddisk\d+",i[1])[0],i[1]))
    g=k[0][0]
    l=os.popen('powershell.exe "Get-PhysicalDisk | Select -Prop DeviceId,FriendlyName,SerialNumber"').read()
    for i in l.splitlines():
        if i.splitlines()!=[]:
            if i.split()[0]==g[-1]:
                harddisk_name=i
    sn= harddisk_name.split()[-1]
    hdn= harddisk_name.split()[1]  
    print("Alert for {0} : Host is reporting disk errors within {1} Hrs.".format(hn,hours))
    print("Harddisk name {0} with serial number {1} is currently reporting errors .".format(hdn,sn))
    print(k[0][1])
    print("The system drive on this host is : {0}.".format(n[-2]))
    alert(1)