#!/bin/sh
#				Script Summary
################################################################################################
# The script is used to manage Schedules Entries in Maintenance Windows
################################################################################################

#Global Defaults
#############################################################
CSV_FILE="input.csv"
CSV_DELIMITER=","
HTTPS_TIMEOUT=30		#seconds
HTTPS_VERIFY_SERVER_CERT=0	#0=false, 1=true
#############################################################

usage () {
    cat <<HELP_USAGE

    Usage:
    	$0  <Manager IP> <User> <API Key> <CSV File> <Action>

	    <Manager IP> - IP Address of the Manager server
	    <User> -       Username on Manager Server for invoking APIs
	    <API Key> -    API Key on Manager Server for invoking APIs
	    <CSV File> -   CSV filename for adding Schedule entries
	                   Format: MaintenanceWindow Name,SchduleEntry Name,Start_Day,End_Day
	                   Ex: AprilWindow,AllDays,2020-03-29 00:00:00,2020-03-31 04:30:00
	    <Action> -     Action on the CSV entries
          	                Options: append/delete/delete_add
                                append - Only add the given csv schedule entries and ignore if entry exists. (with same StartDay and EndDay)
        	                delete - Delete all the Schedule Entries from all the Maintenance Windows
                	        delete_add - Delete all the Schedule Entries from all the Mantainance Windows and then add from CSV file
    Ex:
    	$0  10.10.10.20 netAdmin "XXXX-XXXXX-XXXXXXXXXXX" /home/admin/entries.csv append

    Dependencies: 'curl' and 'jq'

HELP_USAGE
}

if [ $# -eq 0 ]; then
	usage
	exit 1
fi

#Check pre-requisites
CURL_BIN=`which curl`;JQ_BIN=`which jq`;
if [ -z "$JQ_BIN" -o -z "$CURL_BIN" ]; then
	echo "Pre-requisites unmet. Check if curl and jq and installed. Exiting.."
	usage;
	exit 1;
fi
MGR_IP="$1"
if [ -z "${MGR_IP}" ]; then
	echo "Manager IP is missing. EXiting.."
	usage;
	exit 1;
fi


MGR_USER="$2"
if [ -z "${MGR_USER}" ]; then
	echo "Manager Username parameter missing. EXiting.."
	usage;
	exit 1;
fi

API_KEY="$3"
if [ -z "${API_KEY}" ]; then
	echo "API Key missing. EXiting.."
	usage;
	exit 1;
fi

CURL_OPTIONS="${CURL_OPTIONS} --digest -u ${MGR_USER}:${API_KEY}"

CSV_FILE="$4"
if [ ! -f "${CSV_FILE}" ]; then
	echo "CSV file does not exist or is not a regular file. EXiting.."
	usage;
	exit 1;
fi

ACTION="$5"
if [ -z "${ACTION}" ]; then
	echo "Action parameter missing. EXiting.."
	usage;
	exit 1;
fi

if [ ${HTTPS_VERIFY_SERVER_CERT} -eq 0 ]; then
	CURL_OPTIONS="${CURL_OPTIONS} -k"
fi

#Remove carriage returns from CSV file
cat "${CSV_FILE}" | tr -d '\r' > "${CSV_FILE}_fjbewfabc"
mv  -f "${CSV_FILE}_fjbewfabc" "${CSV_FILE}"



	TIME="`date +%s`"
	MW_LIST=$(${CURL_BIN} -m ${HTTPS_TIMEOUT} -f -s  ${CURL_OPTIONS} "https://${MGR_IP}/vmanage-server/rest/experimental/patch-governance/maintenance-windows?timestamp=`date +%s`")
	if [ $? -ne 0 ]; then
		echo " URL not reachable"
		exit 1
	fi

	if [ -z "${MW_LIST}" ]; then
		echo " No Maintenance Windows available for updation"
		exit 1
	fi

	if [ "${ACTION}" = "delete" -o "${ACTION}" = "delete_add" ]; then
		for mw_id in `echo "${MW_LIST}" | jq  '.[] | .id'`
		do
			SCHD_LIST="`${CURL_BIN} -m ${HTTPS_TIMEOUT} -f -s  ${CURL_OPTIONS} https://${MGR_IP}/vmanage-server/rest/experimental/patch-governance/maintenance-window-schedule-times/${mw_id}?timestamp=${TIME}`"
			if [ $? -ne 0 ]; then
				echo "Failed to reach the Manager while getting the Schedule List for Maintenance Window: ${mw_id}"
				exit 1;
			fi
			schd_id_list=""
			for schd_id in `echo "${SCHD_LIST}" | jq  '.schedules| .[] | .id'`
			do
				schd_id_list="${schd_id_list}${schd_id},"
				
			done
			if [ -n "{schd_id_list}" ]; then
				schd_id_list=${schd_id_list%,}
				${CURL_BIN} -X DELETE -m ${HTTPS_TIMEOUT} -f -s  ${CURL_OPTIONS} \
						"https://${MGR_IP}/vmanage-server/rest/experimental/patch-governance/maintenance-schedule-entries/{${schd_id_list}}?timestamp=${TIME}"
			fi
		done
		echo "Deleted all Scheduled entries for Maintenance Window ID: $mw_id"
	fi

	if [ "${ACTION}" = "append" -o "${ACTION}" = "delete_add" ]; then
		TIME="`date +%s`"
		while IFS="${CSV_DELIMITER}" read -r MW_NAME SCHD_NAME START_DAY END_DAY
		do
			if [ -z "${MW_NAME}" -o -z "${SCHD_NAME}" -o -z "${START_DAY}" -o -z "${END_DAY}" ]; then
				logger "Skipping due to incomplete parameters Maintenance Window: ${MW_NAME}, Schedule Name: ${SCHD_NAME}, Start Time: ${START_TIME}, End Time: ${END_TIME}"
				continue;
			fi

			mw_id=`echo "${MW_LIST}" | jq '.[]  | select(.name=='\"${MW_NAME}\"') | .id'`
			SCHD_LIST="`${CURL_BIN} -m ${HTTPS_TIMEOUT} -f -s  ${CURL_OPTIONS} https://${MGR_IP}/vmanage-server/rest/experimental/patch-governance/maintenance-window-schedule-times/${mw_id}?timestamp=${TIME}`"
			if [ -n "${SCHD_LIST}" ]; then
				schd_id=`echo "${SCHD_LIST}" | jq --arg start_day "$START_DAY" --arg end_day "$END_DAY" '.schedules | .[]  | select(.startDay==$start_day and .endDay==$end_day) | .id'`
				if [ -n "$schd_id" ]; then
					STATUS="Schedule Entry Exists"
					echo "${MW_NAME},${SCHD_NAME},${START_DAY},${END_DAY},$STATUS"
					continue;
				fi
			fi

			#Add the manitannace window
			POST_DATA="{\"maintenanceWindowId\" : ${mw_id},\"allDay\":false,\"externalId\":0,\"name\":\"${SCHD_NAME}\",\"notes\":\"\",\"startDay\":\"${START_DAY}\",\"endDay\":\"${END_DAY}\",\"repeatType\":\"\",\"repeatCount\":1,\"repeatUntilDate\":\"3000-01-01 00:00:00\"}"
			${CURL_BIN} -X POST -m ${HTTPS_TIMEOUT}  ${CURL_OPTIONS} -H "Content-Type: application/json" -f -s -d "${POST_DATA}" \
					"https://${MGR_IP}/vmanage-server/rest/experimental/patch-governance/maintenance-schedule-entries?timestamp=${TIME}" > /dev/null
			if [ $? -eq 0 ]; then
				STATUS="Added"
			else
				STATUS="API Failed"
			fi
			echo "${MW_NAME},${SCHD_NAME},${START_DAY},${END_DAY},$STATUS"

		done < "${CSV_FILE}"


	fi
