#!/bin/bash

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

LEDSTATUS=/opt/temp/led/tmp/ledStatus.txt
# This script checks if the radcan program is still running.
#
# The radcan program creates a file $WATCHDOG every ... seconds.
# The time interval is set in radcan.conf file.
#
# If the $WATCHDOG file is not found, then radcan has failed to touch it.
# That may indicate that radcan 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 radcan.conf.
#
# Assuming a random crash of radcan 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
# touching the $WATCHDOG file and for runing the scritp.

if [ -f $WATCHDOG ]; then
   rm $WATCHDOG;
   if [ -f $WATCHDOG_CHECK ]; then
      rm $WATCHDOG_CHECK;
   fi

   # if status is error, maybe some internal module on wgs wrote it and we should keep
   if [ -f $LEDSTATUS ]; then
      # read led status
      status=$(<$LEDSTATUS)
      echo "$status"
      # if status is error, maybe some internal module on wgs wrote it and we should keep
      if [ "$status" == "error" ]; then
      else
         #write status into ledStatus file
         echo "ok" > $LEDSTATUS
      fi     
   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;

      #write status into ledStatus file
      echo "finish" > $LEDSTATUS

      /sbin/reboot &
      sleep 10
      /sbin/reboot -f
   else
      touch $WATCHDOG_CHECK;

      #write status into ledStatus file
      echo "start" > $LEDSTATUS
   fi
fi
