#!/bin/sh
# Modified from xservewatch 8/28/10 M.H. 
# Check if snetmon has modified RRDs in the last 20 min. and restart if not. 
# put this file in /etc/cron.hourly
# modify /etc/crontab to run this as often as you want.  default once/20 min. 
# modified to test for RRD updates rather than pid existence because snetmon hangs not dies.
# tests for counter modification by snetmon. 
# Modified snetmon to update count after every RRD write. M.H. 9/7/10
# Modified again to watch ekotran.pl on eKo Pro systems  4/21/13 M.H. 
# Modified again to watch snetbase on CS3 systems. 5/1/13 M.H. 
# Modified again to watch pcDpush on pcDuino3-Nano systems.  10/23/14

# This file name is pcDpushWatch

# Test how recently the "pushed" file has been touched   If longer than 20 minutes restart. 

cd /home/ubuntu/cs3code  #default dir where pcDpush.pl script being watched is located.

#first calculate the time 20 minutes ago
datesecs=`date +%s`;thresh=`expr $datesecs - 1200`
#This instantiation looks at a file that is touched by  pcDpush.pl when basic functions occur  
echo "Check that /home/ubuntu/cs3code/pushed has been modified(touched) since $thresh"
timeRRDlastModified=`stat -c %Y "/home/ubuntu/cs3code/pushed"` 

currentTime=`date +%s`
echo time RRD last modified   $timeRRDlastModified  #time file was last touched
echo current time             $currentTime   #current time
RRDage=`expr $currentTime - $timeRRDlastModified` 
echo "Time since touch in seconds" $RRDage 
export RRDage
if expr $RRDage \> 1200
  then
    echo $RRDage
    echo "No RRDs have been updated for more than 20 minutes"
    kill `ps -C pcDpush.pl  -o pid  | grep -v PID`   
    # Kills the process running the specified PERL script. Back quote starts system command which starts by 
    # getting process status (ps) for command with the specified name.  The output is the title "PID" and the pid. 
    # The subsequent grep grabs everything but the PID title which will be the pid.  
    #  The kill command then kills the process associated with this pid.  
    echo "killed any residual forms of pcDpush.pl"
    #restart the snetmon.  
    echo "Restarting pcDpush.pl"
     /home/ubuntu/cs3code/pcDpush.pl >/dev/null 2>&1 &
     #this script stops here once the snetmon program starts running again.
     #a new copy of the watch program will be started by cron even if this hangs.
     #Probably should also kill any older copies of this watch program that are running too.
  else
    echo "pcDpush.pl has pushed data to server in the last 20 min., exiting..."  #O.K. to exit. 
fi
exit

