import os
import ssl
import subprocess
import ctypes
import urllib2
import zipfile
import shutil

dIr = r'C:\Windows\Temp'  # change the path if required
Folder_Path = dIr + r'\Trend_Micro_Uninstaller'
URL = r'https://script-downloads.comodo.com/SA_Uninstall.zip'


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, 'SA_Uninstall_1384.zip')
        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 filezip(src_path, destination_path):
    with disable_file_system_redirection():
        with zipfile.ZipFile(src_path, "r") as zip_ref:
            zip_ref.extractall(destination_path)
            print 'file successfully unzipped to ' + destination_path


def ExecuteCmd(cmd):
    with disable_file_system_redirection():
        obj = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = obj.communicate()
        return out, 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


try:
    fs = Download(Folder_Path, URL)
    if os.path.exists(fs):
        ep = os.path.join(Folder_Path, 'Trend-Micro')
        try:
            filezip(fs, ep)
            path = ep + "\\SA_Uninstall\\Uninstall.bat"
            if os.path.exists(path):
                print "Bat file will be located at " + path + " run the bat file manually at safe mode with minimal " \
                                                              "option "
                print "System will reboot to safe mode with minimal option"
                ExecuteCmd('bcdedit /set {default} safeboot minimal')
                os.popen("shutdown -r -t 0")
            else:
                print "Bat file does not exists"
        except Exception as zipErr:
            print zipErr
    else:
        print 'download failed'

except:
    print 'Script execution failed'