import subprocess
import os
import ctypes
import _winreg

nameA = "RoboShadow Update Service (64 Bit)"
nameB = "RoboShadow Agent (64 Bit)"


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(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = obj.communicate()
        ret = obj.returncode
        return out,err, ret


def collectprograms(rtkey, pK, kA):
    try:
        list = []
        oK = _winreg.OpenKey(rtkey, pK, 0, kA)
        i = 0
        while True:
            try:
                bkey = _winreg.EnumKey(oK, i)
                vkey = os.path.join(pK, bkey)
                oK1 = _winreg.OpenKey(rtkey, vkey, 0, kA)
                try:
                    DN, bla = _winreg.QueryValueEx(oK1, 'DisplayName')
                    inlist = [DN.strip(), vkey, pK]
                    list.append(inlist)

                except:
                    pass
                i += 1
            except:
                break
    except:
        pass
    return list


def reg(nameA, nameB):
    uninstallkey_32 = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall'

    if 'PROGRAMFILES(X86)' in os.environ.keys():

        rklist = [(_winreg.HKEY_LOCAL_MACHINE, uninstallkey_32, _winreg.KEY_WOW64_32KEY | _winreg.KEY_READ),
                  (_winreg.HKEY_LOCAL_MACHINE, uninstallkey_32, _winreg.KEY_WOW64_64KEY | _winreg.KEY_READ),
                  (_winreg.HKEY_CURRENT_USER, uninstallkey_32, _winreg.KEY_WOW64_32KEY | _winreg.KEY_READ),
                  (_winreg.HKEY_CURRENT_USER, uninstallkey_32, _winreg.KEY_WOW64_64KEY | _winreg.KEY_READ)]
    else:

        rklist = [(_winreg.HKEY_LOCAL_MACHINE, uninstallkey_32, _winreg.KEY_READ),
                  (_winreg.HKEY_CURRENT_USER, uninstallkey_32, _winreg.KEY_READ)]

    for i in rklist:
        col = collectprograms(i[0], i[1], i[2])
        for c in col:
            prod = c[0].replace('\n', '')
            if nameA in prod or nameB in prod:
                GUID = os.path.basename(c[1])
                command = "MsiExec.exe /X " + GUID + " /qn CESMCONTEXT=1 REBOOT=REALLYSUPPRESS"
                retcd = ExecuteCmd(command)[2]
                print retcd
    Result = ExecuteCmd(['powershell', r'wmic product get name | Select-String -pattern "RoboShadow"'])[0]
    if Result == '':
        print "RoboShadow has been uninstalled successfully"
    else:
        print "RoboShadow is still present on the Endpoint. Uninstallation failed"


reg(nameA, nameB)