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

import cohesityAPI as cohesity
import automationsAPI as dashboard

def GetArgs():
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument('--cluster', '-c', type=str, action='store')
    parser.add_argument('--vcenter', '-v', type=str, action='store')
    parser.add_argument('--type', '-t', type=str, action='store')
    parser.add_argument('--job', '-j', type=str, action='store')
    parser.add_argument('--pause', '-p', action='store_true')
    parser.add_argument('--resume', '-r', action='store_true')
    parser.add_argument('--help', '-h', action='store_true')
    return (parser.parse_args())

def PrintHelp():
    print("\nBasic Usage:")
    print("\n python3 pauseBackups.py -c cluster1.domain.tld -v vCenter.domain.tld [ -t kVMware, kPhysical, kSQL ] [ -p | -r ] [ -j protectionJobName ]")
    print("\t -c FQDN of Cohesity cluster address")
    print("\t -v FQDN of vCenter Server, used in conjuntion with -t kVMware ")
    print("\t -t Cohesity job type, kVMware, kPhysical, kSQL")
    print("\t -j Cohesity job name")
    print("\t -p Pause jobs that match the specified parameters")
    print("\t -r Resume jobs that match the specified parameters")
    print("\t -h Prints this help message")

args = GetArgs()

if args.help:
    PrintHelp()
    exit(1)

if not args.cluster:
    sys.exit("Error: Specify Cohesity cluster fqdn with -c parameter.")
elif args.type == "kVMware" and not args.vcenter:
    sys.exit("Error: Specify vmware cluster address withe -v parameter when using type of kVMware.")
elif args.vcenter and not args.type:
    args.type = "kVMware"
else:
    cluster = cohesity.API(args.cluster) 
    authToken = cluster.GetAuthToken()
    cluster.UpdateHeaders(authToken['accessToken'])

if args.type=='kVMware' and args.vcenter:
    vmSources = cluster.GetFilteredRequest("/public/protectionSources", "?environments=kVMware")

    for source in vmSources:
        if source['protectionSource']['name'] == args.vcenter:
            vCenter = source
            print (vCenter)
            vCenterID = source['protectionSource']['id']
            break

    if args.job:
        vmJobs = cluster.GetFilteredRequest("/public/protectionJobs", "?names=" + args.job)
    else:
        vmJobs = cluster.GetFilteredRequest("/public/protectionJobs", "?environments=kVMware")
        print("Attempting to pause all jobs under " + args.vcenter)

    uniqueJobs = {job['id'] : job for job in vmJobs}.values()

    if args.pause:
        pausedJobs = []
        for job in uniqueJobs:
            if job['parentSourceId'] != vCenterID:
                print("not vcenter")
                continue

            elif "isDeleted" in job:
                continue

            elif "isPaused" in job:
                if job['isPaused']:
                    pausedJobs.append(job)
                    continue
            
            print("Pausing: " + job['name']) 
            resp = cluster.PauseJob(job['id'])

        print("The following jobs were previously paused before this operation.")
        for pJob in pausedJobs:
            print(pJob['name'])

    if args.resume:
        for job in uniqueJobs:
            if job['parentSourceId'] != vCenterID:
                continue
            elif "isDeleted" in job:
                continue
            print("Resuming: " + job['name']) 
            resp = cluster.ResumeJob(job['id'])

dashboard.send_automation({'AutomationName': 'Infra-Cohesity', 'Action': 'Maintenance', 'Platform': 'Python-pauseOrResumeJob.py', 'Units': 60})
