#To define a particular parameter, replace the 'parameterName' inside itsm.getParameter('parameterName') with that parameter's name
import sys
import optparse
import shutil
import os
import subprocess
import getpass
import pwd

def execute(arguments):
    p = subprocess.Popen(arguments, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
    output, error = p.communicate()
    if output is not None and output != '':
        print output
        
def rmtree_if_exists(path):    
    if os.path.exists(path):
        print "removing " + path
        try:
            if os.path.isdir(path):
                shutil.rmtree(path)
            else:
                os.remove(path)
        except Exception as e:
            print(e)
            raise

def start_removing():
    print "stopping daemons..."
    execute(["/bin/launchctl", "unload", "-w", "/Library/LaunchDaemons/com.comodo.fileaccessdaemon.plist"])

    print "unloading kext..."
    execute(["/sbin/kextunload", "-b", "com.comodo.kext.FileAccessFilter"])

    #unload user agents
    uid = pwd.getpwnam(os.getlogin()).pw_uid
    os.seteuid(uid)

    print "stopping agents..."
    execute(["/bin/launchctl", "unload", "-w", "/Library/LaunchAgents/com.comodo.TrayMenu.plist"])
    execute(["/bin/launchctl", "unload", "-w", "/Library/LaunchAgents/com.comodo.ComodoAgent.plist"])
    
    #remove
    os.seteuid(0)
    
    rmtree_if_exists("/Applications/Comodo")
    rmtree_if_exists("/Library/Application Support/Comodo")
    rmtree_if_exists("/Library/Services/Scan with COMODO CLIENT - Security.workflow")
    rmtree_if_exists("/Applications/COMODO CLIENT - Security.app")
	
    execute(["/usr/bin/killall", "FileAccessDaemon"])
    execute(["/usr/bin/killall", "TrayMenu"])    
    execute(["/usr/bin/killall", "Agent"])

    
def main(argv = None):
    parser = optparse.OptionParser(usage = optparse.SUPPRESS_USAGE)
    parser.add_option("-f", "--force", dest = "force", action = "store_true", default = False)
    (options, args) = parser.parse_args()
    start_removing()
        

if __name__ == "__main__":
    sys.exit(main())
