#To define a particular parameter, replace the 'parameterName' inside itsm.getParameter('parameterName') with that parameter's name
import urllib2
import os
import subprocess
import ctypes
import ssl


Url = "https://script-downloads.itarian.com/velociraptor_0.73.3.msi" 


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 Download(src_path, DURL):
    try:
        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
    except:
        return ''


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


with disable_file_system_redirection():
    print('File Downloading')
    destination = os.environ['Temp']
    DownPath = Download(destination, Url)
    if os.path.exists(DownPath):
        print('File downloaded')
        command = 'msiexec /i ' + DownPath + ' /quiet'
        res = ExecuteCmd(command)
        if res[0] == '' and res[1] == '':
            print os.path.basename(DownPath).replace('.msi', '') + "[Successfully Installed]"
        else:
            print "Installation failed"
    else:
        print "Unable to download MSI file provide valid link"