#!/usr/bin/python
import sys,argparse,json,time
import time
sys.path.insert(0, './classes/')

import cohesityAPI as cohesity
import sharePointAPI as sharePoint
import serviceNowAPI as snow
import automationsAPI as dashboard


# Global variables that will be used across all functions
# Begin Functions

def GetArgs():
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument('--cluster', '-c', type=str, action='store')
    parser.add_argument('--verify', '-v', action='store_true')
    parser.add_argument('--help', '-h', action='store_true')
    return (parser.parse_args())

def PrintHelp():
    print("\nBasic Usage:")
    print("\npython3 sqlServerRegistration.py -c cluster.fqdn.tld")
    print("\t -c FQDN of Cohesity cluster address")
    print("\t -v force confirmation on change")
    print("\t -h Prints this help message")

args = GetArgs()

# Validate arguments & assign variables if necessary
if args.help:
    PrintHelp()
    exit(1)

if not args.cluster:
    PrintHelp()
    exit(1)

# ServiceNow object
ticketSystem = snow.SnowAPI("northdakota.service-now.com")

# Sharepoint Object
cmdb = sharePoint.API()

# Connect to the Cohesity cluster
cluster = cohesity.API(args.cluster)
authToken = cluster.GetAuthToken()
cluster.UpdateHeaders(authToken['accessToken'])

vmWareJobs=cluster.GetFilteredRequest("/public/protectionJobs","?environments=kAzureNative&isActive=True")

for job in vmWareJobs:
    preChangeNotes = json.dumps(job)
    if 'name' in job:
        jobName = job['name']

        if '@cares01' in jobName:
            continue
            print("\nUpdating policy for {0}".format(jobName))
            policyData = {"policyId": "7780085755317378:1694019083558:285"

        if '@infra01' in jobName: 
            continue
            print("\nUpdating policy for {0}".format(jobName))
            policyData = {"policyId": "7780085755317378:1694019083558:286"}
            job.update(policyData)  
        
        elif '@npd01' in jobName:
            continue
            print("\nUpdating policy for {0}".format(jobName))
            policyData = {"policyId": "7780085755317378:1694019083558:287"}
            job.update(policyData)  

        elif '@prd01' in jobName:
            print("\nUpdating policy for {0}".format(jobName))
            policyData = {"policyId": "7780085755317378:1694019083558:288"}
            job.update(policyData)  
        
        else:
            continue
        
        if args.verify:
            confirm = input("About to update protection job {0}. Are you sure? [yes|no] ".format(jobName))
        else:   
            confirm = "yes"

        if confirm.lower() == "yes":
            changeID = ticketSystem.CreateStandardChange("NDIT-SPS-Cohesity Data Protection", "NDIT-Cloud Platforms", "svccohesityadm", "ndheck", "mlaverdure", "Computer Systems", "Backup/Restore", "Automated Change - Cohesity job update for {}".format(jobName), "Update protection policy to enable replication.")
            changeSysID = changeID['result']['sys_id']['value']
            ticketSystem.scheduleStandardChange(changeSysID)
            ticketSystem.implementStandardChange(changeSysID)
            ticketSystem.addStandardChangeNotes(changeSysID, "Original job details\n\n{}".format(preChangeNotes))
            ticketSystem.reviewStandardChange(changeSysID)

            updateStats = cluster.UpdateVMProtectionJob(job)

            if updateStats.status_code != 200 and updateStats.status_code != 201:
                postChangeNotes = "Job update failed\n\n" + updateStats.text
                ticketSystem.addStandardChangeNotes(changeSysID, postChangeNotes)
                ticketSystem.closeStandardChange(changeSysID, "Unsuccessful", "Change Failed")
            else:
                postChangeNotes = "Updated the policy\n\n" + updateStats.text
                ticketSystem.addStandardChangeNotes(changeSysID, postChangeNotes)
                ticketSystem.closeStandardChange(changeSysID, "Successful", "Change Complete")

            print("Change {} complete".format(changeID['result']['number']['value']))
