#To define a particular parameter, replace the 'parameterName' inside itsm.getParameter('parameterName') with that parameter's name
import os
import ctypes
import subprocess
import re
import time
import sys

a=0
DownTo = os.environ['TEMP']
fromURL="http://downloads.comodo.com/av/updates58/versioninfo.ini"
fileName = fromURL.split('/')[-1]
fp = os.path.join(DownTo, fileName)

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 check():
    with disable_file_system_redirection():
        inst=os.popen("wmic product get name,identifyingnumber").read()
    return inst
        
def Download(src_path, URL,fp):
    import urllib2
    
    request = urllib2.Request(URL, headers={'User-Agent' : "Magic Browser"})
    try:
        gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        parsed = urllib2.urlopen(request,context=gcontext)
    except:
        parsed = urllib2.urlopen(request)
    if not os.path.exists(src_path):
        os.makedirs(src_path)
    with open(fp, 'wb') as f:
        while True:
            chunk=parsed.read(100*1000*1000)
            if chunk:
                f.write(chunk)
            else:
                break
    return fp

inst=check()
 
if len(inst)>0:
    find=re.findall('{.*}\s\sCOMODO\sClient\s-\sSecurity',inst)
    if len(find)>0:
        final=re.findall('{.*}',find[0])[0]
        if len(final) >0:
            a=1

			
if a ==1:
    curr_db_ver=[]
    max_ver=[]
    
    print ("COMODO Client Security  is installed on Endpoint")

    with disable_file_system_redirection():
        cmd=subprocess.Popen('powershell "Get-CimInstance -Namespace root/cis AvControl"', shell=True, stdout=subprocess.PIPE)
        result=cmd.communicate()
        ret=cmd.returncode
        if ret==0:
            if result[0]:
                res=result[0].strip()
                curr_db_ver = list(res.split(" "))
                print "Current AV DB Version is : "+curr_db_ver[-1]
                             
                path=Download(DownTo, fromURL,fp)
                
                with open(path,'r')as fh:
                    data=fh.readlines()
                    max_ver= list(data[1].split("="))
                    print "Maximum Available AV DB Version is : " +max_ver[-1]
                fh.close()                    

                if int(max_ver[-1]) > int(curr_db_ver[-1]):
                    print "AV Database Update Required!!"
                    cmd=subprocess.Popen('powershell "Invoke-CimMethod -Namespace root/cis AvControl -MethodName UpdateDatabase"', shell=True, stdout=subprocess.PIPE)
                    stdout = cmd.communicate()[0]
                    print stdout
                    print "AV Database Update is Completed!!"
                    
                else:
                    print "AV Database is already Updated!!"
            else:
                print None    
    
else:
    print ("Comodo Client Security is not installed at End point")

if os.path.exists(fp):
    os.remove(fp)
