# To define a particular parameter, replace the 'parameterName' inside itsm.getParameter('parameterName') with that parameter's name
import os
import ctypes
from subprocess import PIPE, Popen


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)


Download_path = os.environ['PROGRAMDATA'] + r'\Background.png'

url = itsm.getParameter('ImgURL')  # Provide an image URL which you want to set as desktop background. the datatype
# should be a string.
# url = "https://www.comodo.com/new-assets/images/comodo-cybersecurity-managed-detection-and-response.png"


Dwn_content = r''' 
$url = "''' + url + '''"

$wc = New-Object System.Net.WebClient
$wc.DownloadFile($url, "''' + Download_path + '''")
'''

PsScript = r'''
$RegKeyPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\PersonalizationCSP"
$PCSP = Get-ItemProperty $RegKeyPath -Name "DesktopImagePath" -ErrorAction SilentlyContinue
if (!$null -eq $PCSP) {
    Remove-ItemProperty -Path $RegKeyPath -Name "DesktopImagePath" -Force
}
if (!(Test-Path -Path $RegKeyPath)){
    New-Item -Path $RegKeyPath
}
$BackGroundImageValue = "''' + Download_path + r'''"
New-ItemProperty -Path $RegKeyPath -Name "DesktopImagePath" -Value $BackGroundImageValue -PropertyType STRING -Force | Out-Null
Stop-Process -processName: Explorer -force
'''


def ecmd(command):
    with disable_file_system_redirection():
        obj = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
    out, err = obj.communicate()
    return err


def CreateScriptFile(ps_content):
    try:
        file_name = 'ScriptFile.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


def RunPowerShellScript(ps_content):
    file_path = CreateScriptFile(ps_content)
    if os.path.exists(file_path):
        if ecmd('powershell "%s"' % file_path) == '':
            return True
        os.remove(file_path)
    else:
        return "Script execution failed"


ecmd(r'powershell "Set-ExecutionPolicy RemoteSigned"')
RunPowerShellScript(Dwn_content)
if os.path.exists(Download_path):
    print "Downloaded successfully to " + Download_path
    if RunPowerShellScript(PsScript):
        print "Script executed successfully"
    else:
        print "Script execution failed"
else:
    print "Download Failed"
