#!/bin/sh

now=`date +%s`
upto=7230
downto=7230
# time shift should be larger than upto and downto by many seconds
timeshift=14400
# time shift check should be smaller than upto and downto by many seconds
timeshiftck=3600

if [ ! -e /var/run/startdate ]; then
	echo $now > /var/run/startdate
fi
if [ ! -e /var/run/lastcheck ]; then
	echo $now > /var/run/lastcheck
fi

startdate=`cat /var/run/startdate`

#delta=`expr $now - $startdate`
#if [ $delta -gt $timeshift ]; then
	#echo $now > /var/run/startdate
#fi

lastcheck=`cat /var/run/lastcheck`

delta=`expr $now - $lastcheck`
if [ $delta -gt $timeshiftck ]; then
	echo $now > /var/run/startdate
	startdate=$now
	echo $now > /var/run/rxcountupdate
	echo $now > /var/run/rxcountdowndate
fi
echo $now > /var/run/lastcheck

if [ -e /var/run/rxcountup ]; then
	echo "$now: rxcountup changed" | logger -p local3.debug -i -t wdcheck
	echo $now > /var/run/rxcountupdate
	rm /var/run/rxcountup
fi

if [ -e /var/run/rxcountdown ]; then
	echo "$now: rxcountdown changed" | logger -p local3.debug -i -t wdcheck
	echo $now > /var/run/rxcountdowndate
	rm /var/run/rxcountdown
fi

if [ -e /var/run/rxcountupdate ]; then
	rxupdate=`cat /var/run/rxcountupdate`
else
	rxupdate=$startdate
fi

delta=`expr $now - $rxupdate`
if [ $delta -gt $upto ]; then
	echo "$now: rxcountup has not changed for $delta seconds, rebooting" | logger -p local3.debug -i -t wdcheck
	exit 1
fi
echo "$now: rxcountup has not changed for $delta ($upto) seconds" | logger -p local3.debug -i -t wdcheck

if [ -e /var/run/rxcountdowndate ]; then
	rxdowndate=`cat /var/run/rxcountdowndate`
else
	rxdowndate=$startdate
fi

delta=`expr $now - $rxdowndate`
if [ $delta -gt $downto ]; then
	echo "$now: rxcountdown has not changed for $delta seconds, rebooting" | logger -p local3.debug -i -t wdcheck
	exit 1
fi
echo "$now: rxcountdown has not changed for $delta ($downto) seconds" | logger -p local3.debug -i -t wdcheck

exit 0
