import os
import ctypes
import ssl
import urllib2
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)


def Download(src_path, URL, fp):
    request = urllib2.Request(URL, 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(fp, 'wb') as f:
        while True:
            chunk = parsed.read(100 * 1000 * 1000)
            if chunk:
                f.write(chunk)
            else:
                break
    return fp


src_path = os.environ['Temp']
URL = "https://script-downloads.comodo.com/Harmony-Connect/harmony-connect-setup-latest.exe"
fp = os.path.join(src_path, 'harmony-connect-setup-latest.exe')
AppLoc = r'C:\Program Files\CheckPoint\Harmony Connect\roaming_service\RoamingServiceLauncher.exe'
AppLoc86 = r'C:\Program Files (x86)\CheckPoint\Harmony Connect\roaming_service\RoamingServiceLauncher.exe'
CMD = fp + r' /S /v/qn'
try:
    if not os.path.exists(AppLoc) and not os.path.exists(AppLoc86):
        Download(src_path, URL, fp)
        if os.path.exists(fp):
            with disable_file_system_redirection():
                obj = Popen(CMD, shell=True, stdout=PIPE, stderr=PIPE)
            out, err = obj.communicate()
            if err != '':
                print err
                print 'Scrip execution failed'
            elif os.path.exists(AppLoc) or os.path.exists(AppLoc86):
                print 'Harmony Connect installed successfully'
            else:
                print 'Scrip execution failed'
    else:
        print 'Harmony connect already exists'
except:
    print 'Scrip execution failed'

if os.path.exists(fp):
    os.remove(fp)
