#! /bin/bash
#
# PURPOSE:      Reset the dropweight watchdog from the ship.
# FIRST AUTHOR: Rob McEwen, 3 Nov 2004, a sad day.
# CHANGE LOG:
#
CNTCT=0    #Contact state.  0 => AUV present; 1 => no contact.
SERVER=0   #Drop weight server state.  1=> Server running; 0=> not running.
FIRST=0
DATE=`date`
LOGNAME=resetdw.log
while [ true ]; do 
    clear;
    echo " "
    echo " "
    if [ $CNTCT = 0 ]; then
	if [ $FIRST = 0 ]; then
	    echo "resetdw is starting..."
	    echo "`date` resetdw is starting..." >> $LOGNAME
	    FIRST=1
	else
	    echo "Contact regained at $DATE"
	    echo "`date` Contact regained at $DATE" >> $LOGNAME
	fi
    else
	echo "Contact lost at $DATE"
	echo "`date` Contact lost at $DATE" >> $LOGNAME
	if [ $SERVER = 1 ]; then
	echo -e '\E[41;41m                                                 '
	echo -e '\E[41;41m                                                 '
	    echo "Drop weight server not running.                  "
	    echo "`date` Drop weight server not running." >> $LOGNAME
	    let TLEFT=(TSTART-$(date +%s))/60
	    if [ $TLEFT -gt 0 ]; then
		echo -e "WEIGHT WILL DROP IN $TLEFT MINUTES.                  "
		echo -e "`date` WEIGHT WILL DROP IN $TLEFT MINUTES." >> $LOGNAME
		if [ $TLEFT -lt 13 ]; then
		    sleep 1
		    echo -e '\E[41;41m \a                                                '
		    sleep 1
		    echo -e '\E[41;41m \a                                                '
		    sleep 1
		    echo -e '\E[41;41m \a                                                '
		fi

	   #echo -e '\E[41;37mWEIGHT WILL DROP IN $TLEFT MINUTES.          '
	    else
		let TSINCE=-$TLEFT
		echo "The weight dropped $TSINCE minutes ago."
		echo "`date` The weight dropped $TSINCE minutes ago.">> $LOGNAME
	    fi
	echo -e '\E[41;41m                                                 '
	echo -e '\E[41;41m                                                 '
	tput sgr0
	else
	    echo "Drop weight server detected."
	    echo "`date` Drop weight server detected." >> $LOGNAME
	fi
    fi
    cat temp.txt | grep DropWeightServer &> /dev/null
    LASTSERVER=$?
    rsh -l dorado1 $AUV_HOST 'if [ `slay -pQ dropWeightServer` ]; then echo "DropWeightServer Detected"; else "reset"; fi' &>temp.txt
    RETVAL=$?
    cat temp.txt >> $LOGNAME
    cat temp.txt
    cp temp.txt tempLast.txt
    if [ $RETVAL != 0 ] ; then
	if [ $CNTCT = 0 ]; then
	    DATE=`date`
	    SERVER=$LASTSERVER
	    let TSTART=$(date +%s)+900
	    cp tempLast.txt tempLost.txt
	fi
	CNTCT=1
	sleep 5
    else
	if [ $CNTCT = 1 ]; then
	    DATE=`date`
	fi
	CNTCT=0
	sleep 10
    fi
done
