#!/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('--jobName', '-p', type=str, action='store')
    parser.add_argument('--newJobName', '-n', type=str, action='store')
    parser.add_argument('--unDelete', '-r', 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 -p Protection job name, use in conjunction with -n")
    print("\t -n New Protection job name, use in conjunction with -p")
    print("\t -r Restore job from a deleted status, only used with single job operations")
    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)

if args.jobName:
    args.verify = True
    if not args.newJobName:
        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'])

if args.jobName:
    vmWareJobs=cluster.GetFilteredRequest("/public/protectionJobs","?names={0}".format(args.jobName))
else:
    vmWareJobs=cluster.GetFilteredRequest("/public/protectionJobs","?environments=kVMware&isActive=True")

for job in vmWareJobs:

    preChangeNotes = json.dumps(job)

    if 'name' in job:
        jobName = job['name']
        oldName = job['name']


        if args.newJobName:
            print("\nUpdating job name for {0}".format(jobName))
            newName = args.newJobName
            jobData = {"name": newName}
            job.update(jobData)  

        if args.unDelete:
            print("\nRestoring job {0} from a deleted state.".format(jobName))
            jobData = {"isDeleted": False}
            job.update(jobData)

        if '@PRD-itd' not in jobName and '@NPD-itd' not in jobName:
            print("\nUpdating job name for {0}".format(jobName))
            x = jobName.split('@')
            newName = x[0] + "@PRD-" + x[1]
            jobData = {"name": newName}
            job.update(jobData)  

            print("Adding the exclude Test tag")
            vcenterSource = cluster.GetFilteredRequest("/public/protectionSources", "?id=" + str(job['parentSourceId']))
            testTagId = cluster.GetVcenterTagId(vcenterSource, 'Test')
            excludeData = {"excludeVmTagIds": [[testTagId]]}
            job.update(excludeData)

            print("Updating to the new Policy Id")
            policy = cluster.GetProtectionPolicyByName("ITD-Bronze-PRD")
            policyData = {"policyId": policy[0]['id']}
            job.update(policyData)

        if args.verify:
            confirm = input("About to update protection job {0}. Are you sure? [yes|no] ".format(oldName))
        else:   
            confirm = "yes"

        if confirm.lower() == "yes":
            changeID = ticketSystem.CreateStandardChange("NDIT-SPS-Cohesity Data Protection", "NDIT-Computer Systems Storage", "svccohesityadm", "ndheck", "mlaverdure", "Computer Systems", "Backup/Restore", "Automated Change - Cohesity job update for {}".format(oldName), "Split production and non-production servers into multiple groups.")
            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 job name, added the exclude test tag, and updated the policy\n\n" + updateStats.text
                ticketSystem.addStandardChangeNotes(changeSysID, postChangeNotes)
                ticketSystem.closeStandardChange(changeSysID, "Successful", "Change Complete")

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