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

import cohesityAPI as cohesity

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

def PrintHelp():
    print("\nBasic Usage:")
    print("\n python3 cancelJobs.py -c cluster1.domain.tld" )
    print("\t -c FQDN of Cohesity cluster address")
    print("\t -h Prints this help message")


args = GetArgs()

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

# Validate arguments & assign variables if necessary
if not args.cluster:
    sys.exit("Error: Specify a Cohesity cluster fqdn with -c parameter.")

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

vmJobs = cluster.GetFilteredRequest("/public/protectionJobs", "?environments=kVMware")
uniqueJobs = {job['id'] : job for job in vmJobs}.values()

# Non Running states
finStates = ['kCanceled', 'kSuccess', 'kFailure', 'kWarning']

for job in uniqueJobs:
    if 'isDeleted' in job:
        continue
    if 'isPaused' in job:
        continue
   
    # Get running protections per vmware protection job id, most recent is returned
    run = cluster.GetFilteredRequest("/public/protectionRuns","?numRuns=10&jobId=" + str(job['id']))

    if run[0]['backupRun']['status'] not in finStates:
        # Cancel the running protection job
        resp = cluster.CancelJob(job['id'],run[0]['backupRun']['jobRunId'])

        # Print the response
        print(resp.content)

