import ctypes
import os
import subprocess

taskName = itsm.getParameter('taskName')  # Change the name if required. New task will be replaced if the task has same name data type should be string
Receiver = itsm.getParameter('EmailTo')  # Provide a Toemail address where the mail need to be sent. the datatype should be a string.
Sender = itsm.getParameter('EmailFrom')  # Provide the From Email address from which the mail to be send. the datatype should be a string.
Password = itsm.getParameter('Password')  # Provide app password for from email. the datatype should be a string.
MailFlag = itsm.getParameter('MailFlag')  # Provide mail flag 1 or 0 (1 - outlook, 0 - gmail). the datatype should be a int.
if MailFlag:
    smtpserver = "smtp.office365.com"
    port = "587"
else:
    smtpserver = "smtp.gmail.com"
    port = "587"


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)


with disable_file_system_redirection():
    username = os.path.basename(os.popen(r'whoami').read()).replace('\n', '')
    sid = os.popen(r'wmic useraccount where name="' + username + r'" get sid').read().splitlines()[1].strip()


def ExecuteCmd(cmd):
    with disable_file_system_redirection():
        obj = subprocess.Popen(["powershell", cmd], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = obj.communicate()
        return out, err


def setTakSchXml(psCommand, args, TaskName):
    XML = r'''<?xml version="1.0" encoding="UTF-16"?>
        <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
          <Triggers>
            <EventTrigger>
              <Enabled>true</Enabled>
              <Subscription>
                &lt;QueryList&gt;&lt;Query Id="0" Path="System"&gt;&lt;Select Path="System"&gt;*[System[Provider[@Name='disk'] and EventID=51]]&lt;/Select&gt;&lt;/Query&gt;&lt;/QueryList&gt;
              </Subscription>
            </EventTrigger>
          </Triggers>
          <Principals>
            <Principal id="Author">
              <UserId>''' + sid + r'''</UserId>
              <RunLevel>HighestAvailable</RunLevel>
            </Principal>
          </Principals>
          <Settings>
            <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
            <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
            <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
            <AllowHardTerminate>true</AllowHardTerminate>
            <StartWhenAvailable>false</StartWhenAvailable>
            <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
            <IdleSettings>
              <StopOnIdleEnd>true</StopOnIdleEnd>
              <RestartOnIdle>false</RestartOnIdle>
            </IdleSettings>
            <AllowStartOnDemand>true</AllowStartOnDemand>
            <Enabled>true</Enabled>
            <Hidden>false</Hidden>
            <RunOnlyIfIdle>false</RunOnlyIfIdle>
            <WakeToRun>false</WakeToRun>
            <ExecutionTimeLimit>PT72H</ExecutionTimeLimit>
            <Priority>7</Priority>
          </Settings>
          <Actions Context="Author">
            <Exec>
                <Command>''' + psCommand + r'''</Command>
                <Arguments>''' + args + r'''</Arguments>
            </Exec>
          </Actions>
        </Task>'''

    ConfigPath = r"C:\Windows\temp\TaskXMLConfig.xml"
    with open(ConfigPath, 'wb') as xmlFile:
        xmlFile.write(XML)
        xmlFile.close()

    cmd = r'schtasks /create /tn "' + TaskName + r'" /XML ' + '"' + ConfigPath + '"'
    if os.path.exists(ConfigPath):
        result = ExecuteCmd(cmd)
        os.remove(ConfigPath)
        if result[0] != '':
            print result[0]
            return True
        else:
            print result[1]
    else:
        print "Config file does not exists"


usrName = os.environ.get('USERNAME')
pscontent = r'''
function Send-ToEmail([string]$sendermail, [string]$email, [string]$smtpserver, [string]$port, [string]$Password, [string]$Body){
    $message = new-object Net.Mail.MailMessage;
    $message.From = $sendermail;
    $message.To.Add($email);
    $message.Subject = "Disk Error on $env:COMPUTERNAME";
    $message.Body = $Body;
    $smtp = new-object Net.Mail.SmtpClient($smtpserver, $port);
    $smtp.EnableSSL = $true;
    $smtp.Credentials = New-Object System.Net.NetworkCredential($sendermail, $Password);
    $smtp.send($message);
    write-host "Mail Sent" ; 
 }

$Body = Get-WinEvent -FilterHashtable @{LogName="System";ID=51;ProviderName='disk'} | Select TimeCreated,Message | select-object -First 1

#Sending an e-mail.
Send-ToEmail  -sendermail "%s" -email "%s" -smtpserver "%s" -port "%s" -Password "%s" -Body "Disk Error on $env:COMPUTERNAME `n`n$Body . UserID : %s";
''' % (Sender, Receiver, smtpserver, port, Password, usrName)


def CreateScriptFile(ps_content):
    try:
        file_name = 'DiskAlertScriptFile.ps1'
        file_path = os.path.join(os.environ['TEMP'], file_name)
        with open(file_path, 'wb') as wr:
            wr.write(ps_content)
            wr.close()
        return file_path
    except:
        return None


scriptFile = CreateScriptFile(pscontent)
if os.path.exists(scriptFile):
    Args = r'-File ' + scriptFile
    ExecuteCmd('Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force')
    ExecuteCmd('Unregister-ScheduledTask -TaskName "' + taskName + '" -Confirm:$false')
    res = setTakSchXml("powershell", Args, taskName)
    if res:
        print "Task Scheduled"
    else:
        print "Task not scheduled"
else:
    print ("Unable to create script file")
