# The script is a template to check UAC status on device. 
import os,platform 
import sys 
import _winreg
import ctypes

def alert(arg): 
   sys.stderr.write("%d%d%d" % (arg, arg, arg)) 

# Please use "alert(1)" to turn on the monitor(trigger an alert) 
# Please use "alert(0)" to turn off the monitor(disable an alert) 
# Please do not change above block and write your script below 

apikey= "95C240FC5936E328161DA1F27171E44D" # String
domain="https://taylor.servicedesk.comodo.com" # String
email="abc@xyz.com" # String
min_count = 2  # Integer Minimum threshold value
max_count = 3 # Integer Maximum threshold value
path = "C:\\" # String Folder path to Monitor

flag=0

def alert(arg): 
   sys.stderr.write("%d%d%d" % (arg, arg, arg)) 

def sd():
    import requests,json,ast
    payload='''{
            "email": "%s",
            "summary": "Monitor File Count in a Directory",
            "description": "SD ticket created when the file count in a directory does not meet condition",
            "assetType": "2",
            "helpTopic": "1",
            "ticketCategory": "17",
            "category": "1"
            }'''%(email)


    url = "%s/clientapi/index.php?serviceName=createticket"%domain


    headers = {
    "Content-Type" : "application/json",
    "Authorization" : "%s"%(apikey)
    }

    response = requests.request("POST", url, data=payload, headers=headers)
    ret=response.status_code
    if ret==200:
        result=response.json()
        if str(result['status'])=="SUCCESS":
            print "Ticket created Successfully on the service desk"
            k1=str(result['data'])
            k2=result['message']
            print '\t',k1.replace('u','').replace(':','').replace('}','').replace('{','').replace("'",'')
            print '\t',k2
        else:
            print "Error on the ticket creation on the service "


def Download(URL, DownloadTo = None, FileName = None):
    import urllib
    import ssl
    if FileName:
        FileName = FileName
    else:
        FileName = URL.split('/')[-1]
        
    if DownloadTo:
        DownloadTo = DownloadTo
    else:
        DownloadTo = os.path.join(os.environ['TEMP'])
        
    DF = os.path.join(DownloadTo, FileName)
    with open(os.path.join(DownloadTo, FileName), 'wb') as f:
        try:
            context = ssl._create_unverified_context()
            f.write(urllib.urlopen(URL,context=context).read())
        except:
            f.write(urllib.urlopen(URL).read())
    if os.path.isfile(DF):
        return DF
    else:
        return False
    
def zip_item(path,final_path):  # Creating ZIP file
    import zipfile
    zip_ref = zipfile.ZipFile(path, 'r')
    zip_ref.extractall(final_path)
    zip_ref.close()
    return final_path

def Import_request(DEST):
    BDPATH = Download(r'https://drive.google.com/uc?export=download&id=1utNFdq-PE8viojsFryrjUYX4bzvNSbW5', FileName = 'requests.zip')
    SRC = os.path.join(os.environ['TEMP'])
    path=zip_item(BDPATH,SRC)
    SRC = os.path.join(os.environ['TEMP'],'requests')
    from distutils.dir_util import copy_tree
    copy_tree(SRC, DEST)
    print "REQUEST IMPORTED SUCCESSFULLY"
    

arch=platform.machine()
if arch=='x86':
    HOMEPATH =r"C:\Program Files"
else:
    HOMEPATH = r"C:\Program Files (x86)"
    
DEST= os.path.join(HOMEPATH,r'COMODO\Comodo ITSM\Lib\site-packages')
Folders=os.listdir(DEST)
Nodow=0
Del_folders=['certifi', 'certifi-2018.10.15.dist-info','chardet', 'chardet-3.0.4.dist-info','requests','requests-2.20.1.dist-info','urllib3','urllib3-1.24.1.dist-info','idna-2.7.dist-info']
for i in Del_folders:
    if i in Folders:
        Nodow=Nodow+1

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)

print ' Monitor for File Count '
print ' *******************************'

with disable_file_system_redirection():
    try:
        count = 0
        count=os.popen( r'powershell " Get-ChildItem '+path+' -File | Measure-Object | %{$_.Count} "').read()
        count_int = int(count)
        if ((count_int < min_count) or (count_int > max_count)):
            alert(1)
            print "File Count in directory "+path+" is: "+count
            if flag!=0:
                if Nodow>7:
                    print "REQUEST AlREADY EXISTS"
                    sd()
                    
            else:
                DEST=Import_request(DEST)
                sd()
        else:
            alert(0)
    except:
        pass
   
