import ctypes
import os
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 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


def RemoveReg(prodDir, prodNm, key, subdir):
    featureKey = ExecuteCmd(r'Get-ChildItem "Registry::' + prodDir + '" -Name')[0].split("\r\n")
    for i in range(len(featureKey) - 1):
        ProdLoc = prodDir + '\\' + featureKey[i]
        prodName = ExecuteCmd(r'(Get-ItemProperty "Registry::' + ProdLoc + '\\' + subdir + '" -Name "' + key + '").' + key)[0]
        if prodNm in prodName:
            ExecuteCmd(r'Remove-Item Registry::"' + ProdLoc + '" -Force -Recurse')
            break


regKey = r'''
Remove-Item -Path HKLM:\SOFTWARE\TrendMicro -Force -Recurse
Remove-Item -Path HKLM:\SOFTWARE\Wow6432node\TrendMicro -Force -Recurse
Remove-Item -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\ApexOneNT -Force -Recurse
Remove-Item -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\ -key Apex One NT Monitor -Force -Recurse
Remove-Item -Path HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\ApexOneNT -Force -Recurse
Remove-Item -Path HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Run -key Apex One NT Monitor -Force -Recurse
Remove-Item -Path HKLM:\SYSTEM\CurrentControlSet\Services\Perf_iCrcPerfMonMgr -Force -Recurse
Remove-Item -Path HKLM:\SYSTEM\CurrentControlSet\Services\TMEBC -Force -Recurse
Remove-Item -Path HKLM:\SYSTEM\CurrentControlSet\Services\tmel -Force -Recurse
Remove-Item -Path HKLM:\SYSTEM\CurrentControlSet\Services\tmnciesc -Force -Recurse
Remove-Item -Path HKLM:\SYSTEM\CurrentControlSet\Services\tmumh -Force -Recurse
Remove-Item -Path HKLM:\SYSTEM\CurrentControlSet\Services\tmWfp -Force -Recurse
Remove-Item -Path HKLM:\SYSTEM\ControlSet001\Services\Perf_iCrcPerfMonMgr -Force -Recurse
Remove-Item Registry::HKEY_CLASSES_ROOT\Installer\Products\1EFA14817AB44D447800A6FC68A0E81D -Force -Recurse
Remove-Item 'C:\Windows\System32\tmumh' -Force -Recurse
Remove-Item 'C:\Windows\SysWOW64\tmumh' -Force -Recurse
Remove-Item 'C:\WINDOWS\system32\Tasks\Trend Micro Apex One Security Services Support Connector' -Recurse
Remove-Item 'C:\ProgramData\Trend Micro' -Recurse
Remove-Item 'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Trend Micro Apex One Security Agent' -Recurse
Unregister-ScheduledTask -TaskName "Trend Micro Apex One Security Services Support Connector" -Confirm:$false
Unregister-ScheduledTask -TaskName "Trend Micro Endpoint Basecamp" -Confirm:$false
Remove-Item 'C:\Program Files (x86)\Trend Micro' -Recurse
Remove-Item 'C:\Program Files\Trend Micro' -Recurse
'''

ExecuteCmd('powershell "Set-ExecutionPolicy RemoteSigned -Force"')
file_path = CreateScriptFile(regKey)
Res = ExecuteCmd('powershell "%s"' % file_path)

prodDirs = [r'HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall|DisplayName|',
            r'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall|DisplayName|',
            r'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products|DisplayName|InstallProperties',
            r'HKEY_CLASSES_ROOT\Installer\Products|ProductName|']


for i in prodDirs:
    SplitValue = i.split("|")
    RemoveReg(SplitValue[0], "Trend Micro", SplitValue[1], SplitValue[2])

pathA = r'C:\Program Files (x86)\Trend Micro'
pathB = r'C:\Program Files\Trend Micro'
if not os.path.exists(pathA) and not os.path.exists(pathB):
    print "Trend micro security agent removed successfully"
else:
    print "Script execution failed"
