import ctypes
import os.path
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 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):
    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 ''


src_path = os.environ['TEMP']
URL = r'https://cdn-patchportal-one.comodo.com/portal/packages/spm/Remote%20Control%20by%20ITarian/x86/RemoteControlbyITarian_8.4.47908.23120.exe'
ExeLoc = Download(src_path, URL)
if os.path.exists(ExeLoc):
    ExecuteCmd(ExeLoc + r' /quiet /norestart')
    PathA = r'C:\Program Files (x86)\ITarian\RemoteControl\RControl.exe'
    PathB = r'C:\Program Files\ITarian\RemoteControl\RControl.exe'
    if os.path.exists(PathA) or os.path.exists(PathB):
        print "Script executed successfully"
    else:
        print "Script execution failed"
    time.sleep(5)
    try:
        os.remove(ExeLoc)
    except:
        pass
else:
    print "Download failed"
