#!/usr/bin/python
import sys
import argparse
import json
import time

sys.path.insert(0, './classes/')
import cohesityAPI as cohesity
import serviceNowAPI as serviceNow
import sharePointAPI as sharePoint
import automationsAPI as dashboard

def GetArgs():
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument('--server', '-s', type=str, action='store')
    parser.add_argument('--protectGroup', '-p', type=str, action='store')
    parser.add_argument('--help', '-h', action='store_true')
    parser.add_argument('--debug', '-d', action='store_true')
    return (parser.parse_args())

def PrintHelp():
    print("\nBasic Usage:")
    print("\npython3 serverRegistration.py -s hostname.nd.gov -p MyApp@physical")
    print("\t -s: Fully qualified domain name of the Server")
    print("\t -p: Protection Group the server is in")
    print("\t -h Prints this help message")

args = GetArgs()

if args.help:
    PrintHelp()
    exit()

if args.debug:
    debugMode = True
else:
    debugMode = False

cluster = cohesity.API('itdmdndpc01.nd.gov')
clusterToken = cluster.GetAuthToken()
cluster.UpdateHeaders(clusterToken['accessToken'])

sourceId = cluster.GetProtectionSourceId(args.server)
pJob = cluster.GetProtectionJobByHost(args.server)

if debugMode:
    print("SourceId:\n==========")
    print(sourceId)

    print("Job Info:\n==========")
    print(pJob)

# If the source is not tied to a protection job we will remove it anyway.
if pJob == -1:
    print("No job was found, continuing to unregister server.")
    removeSourceStat = cluster.RemoveProtectionSource(sourceId)

else:
    if sourceId in pJob['sourceIds']:
        ids = pJob['sourceIds']
        ids.remove(sourceId)
        pJob.update({'sourceIds': ids})

        # Check to see if there are any specific source parameters, if so ensure we clean up those entries as well.
        if 'sourceSpecialParameters' in pJob:
            specialParams = pJob['sourceSpecialParameters']
        
            for entry in specialParams:
                if entry['sourceId'] == sourceId:
                    specialParams.remove(entry)
                    pJob.update({'sourceSpecialParameters': specialParams})

        # Send the updated job information back to the cluster for updating
        updateJobStat = cluster.UpdateProtectionJob(pJob)

        # Ensure the job was updated successfully 
        if updateJobStat.status_code != 200:
            if debugMode:
                print(updateJobStat)
                print(updateJobStat.content)
            sys.exit("Updating the protection job " + pJob['name'] + " failed.\n\nThe source " + args.server + " may be the only source for this job or have special parameters set in the protection job, manual intervention is required to clean up the protection group according to NDIT SLAs.")

        # Attempt to remove the source from the registered sources
        removeSourceStat = cluster.RemoveProtectionSource(sourceId)

# Ensure the source was removed successfully
if removeSourceStat.status_code == 403:
    if debugMode:
        print(removeSourceStat)
        print(removeSourceStat.content)
    sys.exit("Removing " + args.server + " from " + cluster.GetClusterName() + " has failed.")
print(args.server + " has been unregistered from " + cluster.GetClusterName())
dashboard.send_automation({'AutomationName': 'Infra-Cohesity', 'Action': 'DeProvisioning', 'Platform': 'Python-unRegisterServer.py', 'Units': 30})
