#!/bin/bash

export WATCHDOG=/opt/radac/tmp/watchdog
export WATCHDOG_CHECK=/opt/radac/tmp/last-watchdog-check
export WATCHDOGLOG=/root/watchdoglog

# This script checks if the WGS server program (WGS) is still running.
#
# The WGS server program creates a file $WATCHDOG every ... seconds.
# The time interval is set in the wgs.properties file.
#
# If the $WATCHDOG file is not found, then the WGS has failed to touch it.
# That may indicate that the WGS is down. But to make sure that this is not
# the first check after startup the script touchs $WATCHDOG_CHECK file.
# The following time the script is run if $WATCHDOG is still not there.
# Then the system will reboot.
#
# If the $WATCHDOG file does exist, the script will delete it together with 
# $WATCHDOG_CHECK file if it exists.
#
# In order for this to work, the watchdog interval time must be set in wgs.properties.
#
# Assuming a random crash of the WGS we will miss about 30 minutes on
# average, since the WGS only stores data every hour.
# So in case of failure, anything less than 30 minutes should not add too much to the expected dataloss
# Also, booting the WGS can take 1 or 2 minutes, during which time the WGS will not
# create the $WATCHDOG file. So a reasonable period is 300 seconds interval for both
# the touching of the file in wgs.properties and for runing the scritps.

if [ -f $WATCHDOG ]; then
   rm $WATCHDOG;
   if [ -f $WATCHDOG_CHECK ]; then
      rm $WATCHDOG_CHECK;
   fi
else
   if [ -f $WATCHDOG_CHECK ]; then
      echo "===================" >> $WATCHDOGLOG
      echo "Watchdog_radcan: WATCHDOG file not touched for longer than MAXAGE at:" $(date) >> $WATCHDOGLOG
      echo "-------------------" >> $WATCHDOGLOG
      ps ax >> $WATCHDOGLOG
      echo "-------------------" >> $WATCHDOGLOG
      ls -ltra /opt/radac/tmp/ >> $WATCHDOGLOG
      echo "-------------------" >> $WATCHDOGLOG
      echo "Watchdog: rebooting at:" $(date) >> $WATCHDOGLOG
      rm $WATCHDOG_CHECK;
      /sbin/reboot &
      sleep 10
      /sbin/reboot -f
   else
      touch $WATCHDOG_CHECK;
   fi
fi
