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

import cohesityAPI as cohesity
import automationsAPI as dashboard
import nditServiceNow as snow
import random

# Global variables that will be used across all functions

global tagName
tagName = None

# Begin Functions

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('--tag', '-t', type=str, action='store')
    parser.add_argument('--group', '-g', type=str, action='store')
    parser.add_argument('--action', '-a', type=str, action='store')
    parser.add_argument('--list', '-l', type=str, action='store')
    parser.add_argument('--help', '-h', action='store_true')
    return (parser.parse_args())

def PrintHelp():
    print("\nBasic Usage:")
    print("\npython3 updateProtectionGroupTags.py -c hostname.nd.gov")
    print("\t -c FQDN of Cohesity cluster address")
    print("\t -g Protection group name")
    print("\t -a Action to perform 'add' or 'remove'")
    print("\t -l List that needs to be updated, the 'include' or 'exclude'")
    print("\t -h Prints this help message")

args = GetArgs()

if args.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.")


vmObjects = []
protectedObjects = []
# Connect to the Cohesity cluster
cluster = cohesity.API(args.cluster)
authToken = cluster.GetAuthToken()
cluster.UpdateHeaders(authToken['accessToken'])
ticketSystem = snow.SnowAPI("northdakota.service-now.com")
nodes = cluster.GetAZsources()

subscription = input("Which subscription do you want to update? [prd01,npd01,cares01,infra01] ")
if subscription == 'npd01':
    subId = 1
    plcyId = "7780085755317378:1694019083558:287"

elif subscription == 'infra01':
    subId = 28
    plcyId = "7780085755317378:1694019083558:286"

elif subscription == 'prd01':
    subId = 37
    plcyId = "7780085755317378:1694019083558:288"

elif subscription == 'cares01':
    subId = 4
    plcyId = "7780085755317378:1694019083558:285"

sId = subId

nodes = cluster.GetAZsources()

for node in nodes:
    
    if node['protectionSource']['id'] == subscription:
        hypervisorId = node['protectionSource']['id']
        cluster.RefreshSource(node['protectionSource']['id'])

        myObjects = cluster.GetAZObjects(hypervisorId)
        myProtectedObjects = cluster.GetProtectedAZobjects(hypervisorId)

        for val in myObjects:
            vmObjects.append(val)

        for val in myProtectedObjects:
            protectedObjects.append(val)

sourceJobs = cluster.GetAZNativeJobs()

for job in sourceJobs:

    if job['parentSourceId'] != subId:
        continue
    
    print("\nPreparing to update {0}".format(job['name']))
    tagName = job['name'].split('@')[0]
    subName = job['name'].split('@')[1]

    #confirm = input("The tag to protect for this job is {0}. Is that correct? [y/n]".format(tagName))
    confirm = 'y'

    while confirm != 'y' and confirm != 'n':
        confirm = input("Please enter 'y' or 'n': ")

    if confirm == 'n':
        tagName = input("Enter the correct tag: ")
    elif confirm == 'y':

        subSource = cluster.GetFilteredRequest("/public/protectionSources", "?id=" + str(sId))
        tagId = cluster.GetAzureTagId(subSource, tagName)

        changeID = ticketSystem.CreateStandardChange("NDIT-SPS-Cohesity Data Protection", "NDIT-Cloud Platforms", "svccohesityadm", "ndheck", "mlaverdure", "Systems Platforms - Systems", "Backup/Restore", "Automated Change - Update protection job {0}".format(job['name']), "Adjust start time.")
        changeSysID = changeID['result']['sys_id']['value']
        ticketSystem.scheduleStandardChange(changeSysID)
        ticketSystem.implementStandardChange(changeSysID)
        ticketSystem.reviewStandardChange(changeSysID)

        rmin = [0,15,30,45]
        smin = random.choice(rmin)

        rhr = [17,18,19,20,21,22,23,0,1,2,3,4,5]
        shr = random.choice(rhr)

        if(tagId is not None):
            data = {
                "name": job['name'],
                "description": "",
                "policyId": plcyId,
                "storageDomainId": 36,
                "startTime": {
                    "hour": shr,
                    "minute": smin,
                    "timezone": "America/Chicago"
                },
                "priority": "kMedium",
                "sla": [
                    {
                      "backupRunType": "kIncremental",
                      "slaMinutes": 480
                    },
                    {
                      "backupRunType": "kFull",
                      "slaMinutes": 480
                    }
                ],
                "isPaused": False,
                "abortInBlackoutPeriod": False,
                "environment": "kAzure",
                "azureParams": {
                    "protectionType": "kNative",
                    "nativeProtectionTypeParams":{
                        "objects": [],
                        "vmTagIds": [
                            [
                                tagId
                            ]
                        ],
                        #"excludeVmTagIds": False,
                        "indexingPolicy":{
                            "enableIndexing": True,
                            "includePaths": [
                                "/"
                            ],
                            "excludePaths": [
                                "/$Recycle.Bin",
                                "/Windows",
                                "/ProgramData",
                                "/System Volume Information",
                                "/Users/*/AppData",
                                "/Recovery",
                                "/usr",
                                "/sys",
                                "/proc",
                                "/lib",
                                "/grub",
                                "/grub2",
                                "/splunk",
                            ]
                        },
                    },
                },
                "abortInBlackoutPeriod": False
            }

            job.update(data)
            resp = cluster.UpdateAZprotectionJob(job)
            postChangeNotes = resp.text
            ticketSystem.addStandardChangeNotes(changeSysID, postChangeNotes)
            ticketSystem.closeStandardChange(changeSysID, "Successful", "Change Complete")

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