#!/usr/bin/bash


TEXT_STATUS=${TEXT_STATUS:=/media/shared/status}

CONFIG=${CONFIG:=/etc/pve/nodes/pve/config}

# NOTE: since proxmox monitors files, it is better modify the file in 
#		one go but since checking can not be done in an instant we write 
#		the check results to $TMP_RESULTS and when done will swap it with
#		$CONFIG...
# XXX move this to /tmp???
TMP_RESULTS=${TMP_RESULTS:=${CONFIG}.live}


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

source .pct-helpers


#----------------------------------------------------------------------

DATE=`date +'%Y-%m-%d %H:%M'` 

if [ -e $TMP_RESULTS ] ; then
	rm -f $TMP_RESULTS
fi

if [ -e $TEXT_STATUS ] ; then
	mv -f $TEXT_STATUS{,.old}
	echo $DATE > $TEXT_STATUS
else
	TEXT_STATUS=/dev/null
fi


# read the sites from the status section in $CONFIG...
readarray -t lines <<<$(\
	sed -n '/STATUS BEGIN/,/STATUS END/p' "$CONFIG" \
		| sed \
			-e '1d;$d' \
			-e 's/^#//' \
			-e 's/%3A/:/g' \
			-e 's/ : \(OK\|**ERROR\).*//')

# fill the status section -> $TMP_RESULTS...
cp -f "$CONFIG" "$CONFIG".bak
{
	echo '#<!-- STATUS BEGIN -->'
	for line in "${lines[@]}" ; do
		# empty lines...
		if [[ "$line" =~ ^[[:space:]]*$ ]] ; then
			echo "#"
			continue
		# skip check date...
		elif [[ "$line" =~ ^_\(checked[[:blank:]]on:[[:blank:]].*\)_$ ]] ; then
			continue
		fi

		./check-status "$line" \
			| tee -a $TEXT_STATUS \
			| sed \
				-e 's/^\(.*\)\(ERROR.*$\)/\1**\2**/' \
				-e 's/^/#/'
	done
	echo "#_(checked on: ${DATE})_"
	echo '#<!-- STATUS END -->'
} \
	| fillsection -r STATUS ${CONFIG} \
	> "$TMP_RESULTS"


# replace $TMP_RESULTS -> $CONFIG
if [ -e $TMP_RESULTS ] ; then
	mv -f "$TMP_RESULTS" "$CONFIG"
fi


# vim:set ts=4 sw=4 nowrap :
