#!/bin/bash
# set -x

####################################################################################################
# Script Name:  Get-WatchDogMDMClientHealth.sh
# By:  Zack Thompson / Created:  11/4/2023
# Version:  1.0.0 / Updated:  11/4/2023 / By:  ZT
#
# Description:  This script checks the health of the MDM Client and MDM Software Update processes.
#
#	Pass [--debug | -d ] as an argument to "test" the script and not write to the local EA files.
#
####################################################################################################

##################################################
# Set variables for your environment

# The Addigy MDM Watchdog reports various heath info, select one for this script to collect
# and report back to Jamf Pro.
	# MDMEnrolled
	# MDMIdentityError
	# MDMClientStuck
	# MDMSoftwareUpdatesStuck
	# MDMClientRestarted
	# SoftwareUpdateDaemonRestarted
	# LastMDMKickstart
	# LastSoftwareUpdateDaemonKickstart
health_fact="MDMIdentityError"

# The date format expected from date fields generated by `mdm-watchdog`.
default_date_format="%Y-%m-%d %H:%M:%S %z"

# The format of the date string that will be used for reporting.
jamfpro_ea_date_format="%Y-%m-%d %H:%M:%S"

# Locally log EA value for historical reference (since Jamf Pro only ever has the last value).
# Supported actions:
#   true - Do locally Log
#   false - Do not log locally
locally_log="true"
local_ea_history="/opt/ManagedFrameworks/EA_History.log"
local_ea_history_identifier="MDM Watchdog > ${health_fact}:  "
local_ea_inventory="/opt/ManagedFrameworks/Inventory.plist"
local_ea_inventory_identifier="mdm_watchdog_${health_fact}"
debugging_description="Get-WatchDogMDMClientHealth.sh:  "

##################################################
# Functions

arg_parse() {
	# Command Line Argument Parser

	while (( "$#" )); do
		# Work through the passed arguments

		case "${1}" in
			-d | --debug )
				debug="true"
				write_to_ea_history "DEBUGGING ENABLED" "${debugging_description}"
			;;
			# * )
			# 	switch="${1}"
			# 	shift
			# 	value="${1}"
			# 	eval "${switch}"="'${value}'"
			# ;;
		esac

		shift
	done
}

write_to_ea_inventory() {

	# Arguments
	# $1 = (str) Plist key that the message value will be assigned too
	# $2 = (str) Message that will be assigned to the key

	local key="${1}"
	local value="${2}"

	if [[ "${locally_log}" == "true" && -z "${debug}" ]]; then

		if [[ ! -e "${local_ea_inventory}" ]]; then

			/bin/mkdir -p "$( /usr/bin/dirname "${local_ea_inventory}" )"
			/usr/bin/touch "${local_ea_inventory}"

		fi

		/usr/bin/defaults write "${local_ea_inventory}" "${key}" "${value}"

	fi

}

write_to_ea_history() {

	# Arguments
	# $1 = (str) Message that will be written to a log file

	local message="${1}"

	time_stamp=$( /bin/date +%Y-%m-%d\ %H:%M:%S )

	if [[ "${locally_log}" == "true" && -z "${debug}" ]]; then

		if [[ ! -e "${local_ea_history}" ]]; then

			/bin/mkdir -p "$( /usr/bin/dirname "${local_ea_history}" )"
			/usr/bin/touch "${local_ea_history}"

		fi

		echo "${time_stamp} | ${local_ea_history_identifier}${message}" >> "${local_ea_history}"

	else

		echo "${time_stamp} | ${local_ea_history_identifier}${message}"

	fi

}

report_result() {

	# Arguments
	# $1 = (str) Message that will be recorded to the configured locations

	local message="${1}"

	write_to_ea_history "${message}"
	write_to_ea_inventory "${local_ea_inventory_identifier}" "${message}"
	echo "<result>${message}</result>"
	exit 0

}

convert_date(){

	# Convert a formatted date string into another format
	# Arguments
	# $1 = (str) a date in string format
	# $2 = (str) the expected format of the date string
	# $3 = (str) the desired format of the string

	/bin/date -j -f "${2}" "${1}" +"${3}" 2>/dev/null

}

##################################################
# Command Line Argument Parser

parameters=( "$@" )
arg_parse "${parameters[@]}"

##################################################
# Bits staged, collect the information...

if [[ -e "/usr/local/bin/mdm-watchdog" ]]; then

	watchdog=$( /usr/bin/log show --predicate 'process = "mdm-watchdog"' )
	watchdog_stats="${watchdog##*watchdog: }"

	result=$(
		/usr/bin/awk -F "${health_fact}: " '{print $2}' <<< "${watchdog_stats}" | /usr/bin/xargs )

	if [[
		"${health_fact}" == "LastMDMKickstart" ||
		"${health_fact}" == "LastSoftwareUpdateDaemonKickstart"
	]]; then

		if [[ "${result}" == "0001-01-01 00:00:00 +0000 UTC" ]]; then

			report_result "Never"

		else

			# Drop milliseconds
			result=$( /usr/bin/sed -E "s/[.][0-9]+ -/ -/g" <<< "${result}" )

			# Convert date for logging
			report_result "$(
				convert_date "${result}" "${default_date_format}" "${jamfpro_ea_date_format}"
			)"

		fi

	else

		report_result "${result}"

	fi

else

	report_result "Watchdog Not Installed"

fi
