#To define a particular parameter, replace the 'parameterName' inside itsm.getParameter('parameterName') with that parameter's name
import ctypes
import os
import ssl
import subprocess
import time
import urllib2


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 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 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 Download(src_path, DURL):
    filepath = os.path.join(src_path, os.path.basename(DURL))
    request = urllib2.Request(DURL, headers={'User-Agent': "Magic Browser"})
    try:
        gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        parsed = urllib2.urlopen(request, context=gcontext)
    except:
        parsed = urllib2.urlopen(request)
    if not os.path.exists(src_path):
        os.makedirs(src_path)
    with open(filepath, 'wb') as f:
        while True:
            chunk = parsed.read(100 * 1000 * 1000)
            if chunk:
                f.write(chunk)
            else:
                break
    return filepath


src_path = os.environ['Temp']
arch = os.popen("wmic os get OSArchitecture").read()
if '64' in arch:
    URL = r'https://script-downloads.itarian.com/FirefoxSetup.exe'
else:
    URL = r'https://script-downloads.itarian.com/FirefoxSetup-32.exe'

pathA = r'C:\Program Files\Mozilla Firefox\firefox.exe'
PathB = r'C:\Program Files (x86)\Mozilla Firefox\firefox.exe'

if not os.path.exists(pathA) and not os.path.exists(PathB):
    exeFolder = Download(src_path, URL)
    if os.path.exists(exeFolder):
        ExecuteCmd(exeFolder + r' /S')
        if os.path.exists(pathA) or os.path.exists(PathB):
            print 'Script executed successfully'
        else:
            print 'Script execution failed'
        try:
            time.sleep(3)
            os.remove(exeFolder)
        except:
            pass
    else:
        print 'Download failed'
else:
    print 'Firefox already exists'
