options = itsm.getParameter('options') # the options parameter TYPE should be integer.
"""
give 1 in the "options" Parameter if you want to clean up caches files on the endpoint machine.
give 2 in the "options" Parameter if you want to clean up logs files on the endpoint machine.
give 3 in the "options" Parameter if you want to verify volume and repair if any problem.
give 0 in the "options" Parameter if you want to perform all the above.
"""

import subprocess
import os

users = os.popen("ls /Users").read().split()
print(users)
def execute(arguments):
    p = subprocess.Popen(arguments, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True)
    output, error = p.communicate()
    ret = p.returncode
    return (ret,output,error)

def Clearing_CacheAndlogs(users):
    for i in users:
        cachePath = "/Users/%s/Library/Caches"%(i)
        logsPath = "/Users/%s/Library/Logs"%(i)
        if os.path.exists(cachePath) and options==1 or options==0:
            print(os.popen("rm -rf /Users/%s/Library/Caches/*"%(i)).read())
            print("successfully cleaned the path %s"%(cachePath))
        if os.path.exists(logsPath) and options==2 or options==0:
            print(os.popen("rm -rf /Users/%s/Library/Logs/*"%(i)).read())
            print("successfully cleaned the path %s"%(logsPath))

if options == 1 or options == 0:
    system_cache_clearing = os.popen("rm -rf /Library/Caches/*").read()
    print(system_cache_clearing)
    system_logs_clearing = os.popen("rm -rf /LibraryLogs/*").read()
    print(system_logs_clearing)
    flush_caches = os.popen("dscacheutil -flushcache").read()
    print(flush_caches)

if options == 1 or options == 0 or options == 2:
    Clearing_CacheAndlogs(users)

def verifyvolume():
    ret,output,error = execute("diskutil verifyvolume /")
    if ret==0:
        if output:
            if "found corrupt and needs to be repaired" in str(output):
                print("default drive found to be corrupted. initializing repair")
                print(os.popen("diskutil repairvolume /").read())
            else:
                print(output)
        else:
            print("return code: 0")
    else:
        print("there has been an error occured")
        print(error)

if options==3 or options==0:
    verifyvolume()