#!/bin/bash

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/bin/X11:/usr/local/bin:/usr/local/sbin:/usr/fallback

VERSION=3

CFG_FILE='/usr/conf/berofix.conf'
IFACE=eth0
RCV_PORT=65003


#
## Helper Functions
#

cfg.parser () {
	local IFS=$'\n' && ini=( $(<$1) )              # convert to line-array
	ini=( ${ini[*]//;*/} )                   # remove comments
	ini=( ${ini[*]/#[/\}$'\n'cfg.section.} ) # set section prefix
	ini=( ${ini[*]/%]/ \(} )                 # convert text2function (1)
	ini=( ${ini[*]/=/=\( } )                 # convert item to array
	ini=( ${ini[*]/%/ \)} )                  # close array parenthesis
	ini=( ${ini[*]/%\( \)/\(\) \{} )         # convert text2function (2)
	ini=( ${ini[*]/%\} \)/\}} )              # remove extra parenthesis
	ini[0]=''                                # remove first element
	ini[${#ini[*]} + 1]='}'                  # add the last brace
	eval "$(echo "${ini[*]}")"               # eval the result
}

function get_bfxmac() {
	ret=`ifconfig | grep eth0`
	ret=${ret/*HWaddr /}
	echo ${ret:0:17}
}

function get_packetmac() {
	echo ${1:0:17}
}

function get_hoststatus() {
	echo ${1:18:9}
}

function reset_host() {
	echo "WATCHDOG: RESETTING HOST"
	echo 0 > /proc/WATCHDOG_HOST
	sleep 1
	echo 1 > /proc/WATCHDOG_HOST
}


#
## Receiving Functions
#

function get_netpacket() {

	time_remain=${1}
	bfx_mac=$(get_bfxmac)
	while [ ${time_remain} -gt 0 ]; do
		wd_packet=$(echo | nc -q0 -w 1 -lup ${RCV_PORT} 2>/dev/null)
		if [ "$(get_packetmac ${wd_packet})" = "${bfx_mac}" ]; then
			break
		else
			unset wd_packet
		fi
		let time_remain="${time_remain}-1"
	done
	echo ${wd_packet}
}

function get_initpacket() {
	
	bfx_mac=$(get_bfxmac)
	while true; do
		wd_packet=$(echo | nc -q0 -lup ${RCV_PORT})
		if [ "$(get_packetmac ${wd_packet})" = "${bfx_mac}" ]; then
			break
		else
			unset wd_packet
		fi
	done
	echo ${wd_packet}
}

#
## Main Stuff
#

if [ -f ${CFG_FILE} ]; then
	cfg.parser ${CFG_FILE}
	cfg.section.watchdog
else
	wd_mode="manual"
	wd_timeout="5"
fi

while true; do
	ENABLE="no"
	wd_packet=$(get_initpacket)
	wd_status=$(get_hoststatus ${wd_packet})

	if [ "${wd_mode}" = "manual" ] && [ "${wd_status}" = "ENABLE" ]; then
		ENABLE="yes"
		echo "WATCHDOG: ENABLED"
	elif [ "${wd_mode}" = "auto" ] && [ "${wd_status}" = "HOSTALIVE" ]; then
		ENABLE="yes"
		echo "WATCHDOG: ENABLED"
	fi

	while [ "${ENABLE}" = "yes" ]; do
		wd_packet=$(get_netpacket ${wd_timeout})
		wd_status=$(get_hoststatus ${wd_packet})

		if [ "${wd_status}" = "DISABLE" ]; then
			ENABLE="no"
			echo "WATCHDOG: DISABLED"
		elif [ "${wd_status}" != "HOSTALIVE" ]; then
			reset_host
			ENABLE="no"
			break
		fi
	done
done
