UninstallCCS = "yes"
ComodoUninstallerTool = "yes"
DownloadComodoUninstallerToolfromComodo = "yes"
UninstallCCC = "yes"

import os
from subprocess import PIPE, Popen
import shutil
import ctypes
import re
import datetime
import platform
import subprocess
try:
    import winreg as _winreg
except ImportError:
    try:
        import _winreg
    except ImportError:
        pass
import ssl
import time
try:
    import urllib.request as urllib2
except ImportError:
    try:
        import urllib2
    except ImportError:
        pass

min = '10'
datenow = datetime.datetime.now()
datestamp = datenow + datetime.timedelta(minutes = int(min) -1)
CCCStamp = datenow + datetime.timedelta(minutes = 2)
appname = "COMODO Client - Security"
appname2 = "Endpoint Manager Communication Client"

# associated with CCS uninstall
def reg(name):
    blacklist=name
    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
    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)]
    bet=[]
    for i in rklist:
        col=collectprograms(i[0], i[1], i[2])
        for c in col:
            if blacklist in c:
                bet.append(c[1])
    if not bet:
        print ("Please blacklist Valid Installed Software")
        got=0
    else:
        for i in bet:
            j=i.replace(" ", '" "')
            v='\\'
            path="HKEY_LOCAL_MACHINE"+v+i
            path1="HKEY_LOCAL_MACHINE"+v+j
            got=path1        
    return got

# associated with CCS uninstall
def uninstall (find):
	command="MsiExec.exe /X"+find+" /qn CESMCONTEXT=1 REBOOT=REALLYSUPPRESS"
	uninst=os.popen(command).read()
	time.sleep(150)
	fin=reg(appname)
	if fin!=0:
		print ("%s is still present on the Endpoint. Uninstallation failed" % appname)
	else:
		print ("%s has been uninstalled successfully" % appname)

# Uninstall CCS
def CCSUninstall():
	fin=reg(appname)
	if fin!=0:
	    fina=fin.split('\\')[-1]
	    final1=re.findall('{.*}',fina)[0]
	    print ("GUID from Registry is : "+final1)
	    print ("%s is installed on the Endpoint" % appname)
	    print ("Uninstalling has started ")
	    uninstall(final1)
	else:
	    print ("%s is not installed on the Endpoint" % appname)

def FindCCC():
	fin=reg(appname2)
	if fin!=0:
	    fina=fin.split('\\')[-1]
	    final1=re.findall('{.*}',fina)[0]
	else:
	    final1=""
	return final1

def UninstallCCC1():
    # print (str(CCCStamp.hour) + r':' + str(CCCStamp.minute))
    # print (str(CCCStamp.month) + r'/' + str(CCCStamp.day) + r'/' + str(CCCStamp.year))
    CCCGUIDFind = str(FindCCC())
    CCCStampmin = ""
    if CCCStamp.minute < 10:
        CCCStampmin = "0" + str(CCCStamp.minute)
    else:
        CCCStampmin = str(CCCStamp.minute)
    CCCStamphour = ""
    if CCCStamp.hour < 10:
        CCCStamphour = "0" + str(CCCStamp.hour)
    else:
        CCCStamphour = str(CCCStamp.hour)
    # print(CCCGUIDFind)
    dateweneed = os.popen("date /t").read()
    dateweneed = dateweneed.rstrip()
    if len(dateweneed) > 10:
        dateweneed = dateweneed[-10:]
    print(r'schtasks /ru "SYSTEM" /create /tn CCCUninstall /tr "MsiExec.exe /X ' + CCCGUIDFind + r' /qn" /sc once /sd ' + dateweneed + ' /st ' + CCCStamphour + r':' + CCCStampmin + r' /F')
    print(ecmd(r'schtasks /ru "SYSTEM" /create /tn CCCUninstall /tr "MsiExec.exe /X ' + CCCGUIDFind + r' /qn" /sc once /sd ' + dateweneed + ' /st ' + CCCStamphour + r':' + CCCStampmin + r' /F'))

def GetWindowsEdition(Key_name):
	val = ""
	try:
		reg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
		ok = _winreg.OpenKey(reg, Key_name, 0, _winreg.KEY_WOW64_32KEY | _winreg.KEY_READ)
		val = _winreg.QueryValueEx(ok, "ProductName")[0]
		_winreg.CloseKey(ok)
		return val
	except Exception as exception:
		val = "Windows Registry Exception: " + str(exception)
		return val

WindowsVersion = GetWindowsEdition('SOFTWARE\Microsoft\Windows NT\CurrentVersion')

class disable_file_system_redirection:
        try:
            _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)
        except:
            pass

def ecmd(command, output=False):
    if not ("XP" in WindowsVersion or "2008" in WindowsVersion):
        with disable_file_system_redirection():
            objt = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
            out, err = objt.communicate()
            ret = objt.returncode
    else:
        objt = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
        out, err = objt.communicate()
        ret = objt.returncode
    if not out:
        return ret
    else:
        return '%s\n%s' % (out, err)

def checkCCS():
	if os.path.exists(os.environ['systemdrive'] + '\Program Files\COMODO\COMODO Internet Security\cmdagent.exe'):
		return True
	return False

def checkCCC():
	if os.path.exists(os.environ['systemdrive'] + '\Program Files\ITarian\Endpoint Manager\ITSMAgent.exe') or os.path.exists(os.environ['systemdrive'] + '\Program Files (x86)\ITarian\Endpoint Manager\ITSMAgent.exe'):
		return True
	return False

def ComodoUninstallTool():
    if DownloadComodoUninstallerToolfromComodo is "yes":
        # Checks type of the system
        OsComodoUninstallTool = r"C:\Program Files (x86)"
        URL=""
        if os.path.exists(OsComodoUninstallTool):
            # system is 64 bit
            URL=r'http://download.comodo.com/cis/download/installs/ciscleanuptool/ciscleanuptool_x64.exe'
        else:
            # system is 32 bit
            URL=r'http://download.comodo.com/cis/download/installs/ciscleanuptool/ciscleanuptool_x86.exe'
        DownloadPath=os.environ['PROGRAMDATA']
        FileName=r'ciscleanuptool'
        Extension=r".exe"
        # If pattern is given, converts to real path
        def PaternPath(DownloadPath):
            if not os.path.isdir(DownloadPath):
                return ExecuteCMD('echo '+DownloadPath, True)
            return DownloadPath
        # Downloads application
        def Download(Path, URL, FileName,Extension):
            fn = FileName + Extension
            fp = os.path.join(Path, fn)
            req = urllib2.Request(URL, headers={'User-Agent' : "Magic Browser"})
            con = urllib2.urlopen(req)
            with open(fp, 'wb') as f:
                while True:
                    chunk=con.read(100*1000*1000)
                    if chunk:
                        f.write(chunk)
                    else:
                        break
            if os.path.exists(fp):
                return fp
            return False
        # print Path
        Path=PaternPath(DownloadPath)
        # print FilePath
        FilePath=Download(Path, URL, FileName,Extension)
        # Download and run commands
        if os.path.exists(Path):
            pf=FilePath
            if os.path.isfile(pf):
                ec='"%s" -silent'%pf
                print(ec)
                OBJ = Popen(ec, shell = True, stdout = PIPE, stderr = PIPE)
                out, err = OBJ.communicate()
                RET = OBJ.returncode
                if RET == 0:
                    print("Comodo Uninstaller Tool command successful")
                else:
                    print("Comodo Uninstaller Tool command is NOT successful")
    else:
        print("Comodo Uninstaller Tool will be copied from a shared folder")
        # Checks type of the system
        OsComodoUninstallTool = r"C:\Program Files (x86)"
        Source_Path = SharedFolderComodoUninstallerTool
        EnvTemp = os.environ['PROGRAMDATA']
        Dest_Path = os.path.join(EnvTemp, r'Comodo')
        SP_64 = ""
        DP_64 = ""
        SP_86 = ""
        DP_86 = ""
        if not os.path.exists(Dest_Path):
            os.makedirs(Dest_Path)
            print("Comodo Uninstaller Tool destination path was created")
        if os.path.exists(OsComodoUninstallTool):
            SP_64 = os.path.join(Source_Path, ComodoUninstallerToolx64Name)
            DP_64 = os.path.join(Dest_Path, ComodoUninstallerToolx64Name)
            try:
                os.remove(DP_64)
            except OSError:
                pass
            shutil.copy(SP_64, DP_64)
            if os.path.getsize(SP_64) == os.path.getsize(DP_64):
                print("Comodo Uninstaller Tool was copied successfully")
            else:
                print("Comodo Uninstaller Tool was NOT copied successfully")
                exit(code=1)
            time.sleep(10)
            print ("Comodo Uninstaller Tool has started")
            with disable_file_system_redirection():
                print(ecmd(r'"' +  DP_64 + ' -silent', True))
        else:
            SP_86 = os.path.join(Source_Path, ComodoUninstallerToolx86Name)
            DP_86 = os.path.join(Dest_Path, ComodoUninstallerToolx86Name)
            try:
                os.remove(DP_86)
            except OSError:
                pass
            shutil.copy(SP_86, DP_86)
            if os.path.getsize(SP_86) == os.path.getsize(DP_86):
                print("Comodo Uninstaller Tool was copied successfully")
            else:
                print("Comodo Uninstaller Tool was NOT copied successfully")
                exit(code=1)
            time.sleep(10)
            print ("Comodo Uninstaller Tool has started")
            with disable_file_system_redirection():
                print(ecmd(r'"' +  DP_86 + ' -silent', True))

if checkCCS():
    print("Comodo Client - Security is installed on the End point")
    if ComodoUninstallerTool is "yes":
	    ComodoUninstallTool()
    else:
	    CCSUninstall()
else:
    print("Comodo Client - Security is not installed on the End point")

if checkCCC():
    print("Comodo Communication Client is installed on the End point")
    UninstallCCC1()
else:
    print("Comodo Communication Client is not installed on the End point")