import ctypes
import os
import shutil
import subprocess


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 delService():
    with disable_file_system_redirection():
        os.popen('SC Delete SBAMSvc &  SC Delete SBHIPS')


def RemoveReg():
    prodDir = r'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products'

    featureKey = ExecuteCmd(r'Get-ChildItem "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion'
                            r'\Installer\UserData\S-1-5-18\Products\" -Name')[0].split("\r\n")
    for i in range(len(featureKey) - 1):
        ProdLoc = prodDir + '\\' + featureKey[i]
        prodName = ExecuteCmd(r'(Get-ItemProperty "Registry::' + ProdLoc + r'\InstallProperties" -Name '
                                                                           r'"DisplayName").DisplayName')[0]
        if "VIPRE Business Agent" in prodName:
            result = ExecuteCmd(r'REG DELETE ' + ProdLoc.replace('HKEY_LOCAL_MACHINE', 'HKLM') + ' /f')[0]
            if result != '':
                print result + "VIPRE Business Agent uninstalled successfully"
                return True


def RemoveBA(BApath):
    CMD = ''
    if os.path.isfile(BApath + r'\AgentUninstallPassword.exe'):
        with disable_file_system_redirection():
            CMD = os.popen('wmic product where name="VIPRE Business Agent" call uninstall').read()
    if 'ReturnValue = 0;' in CMD or 'No Instance' in CMD or CMD == '':
        delService()
        if 'VIPRE' in BApath:
            try:
                shutil.rmtree(BApath)
                if not RemoveReg():
                    return False
                else:
                    return True
            except:
                pass


def uninstallVipreBA():
    pathA = r'C:\Program Files (x86)\VIPRE Business Agent'
    pathB = r'C:\Program Files\VIPRE Business Agent'
    if os.path.exists(pathA):
        return RemoveBA(pathA)
    elif os.path.exists(pathB):
        return RemoveBA(pathB)
    else:
        print 'VIPRE Business Agent Does Not Exists'
        return True


FinalResult = uninstallVipreBA()
if not FinalResult or FinalResult is None:
    print 'Script execution failed'

