#!/bin/bash
#
# This script is run from cron, and will check for previous auto connection
# by looking for the 'flag' file $LOCAL/ra_connect_id which is created by the
# reflect_auto_connect script.  It is a copy of the 'active' flag set at the
# time of connection. If the flag matches the current active flag the connection
# is cleared down.  This script will clear the ra_connect_id flag if it exists
# and clear the CWID block if it exists.
#
# V1.0 02/02/2009 - VK8SJ - Original version
# V1.1 09/02/2009 - VK8SJ - Add CWID check & restore
# V1.2 12/04/2010 - VK8SJ - Add check for auto-reconnect
# V2.0 25/04/2010 - VK8SJ - Add restore timeout value
# V2.1 24/03/2019 - VK2YLD - Add check to re-enable DTMF controls
#
#
######################################################################
#
# This function logs Date etc then message..
#
function writelog () {
  echo $@
  MESSAGE="`date '+%b %d %Y %T'` "$@
  if [ -n "$LOGFILE" ]; then
    echo $MESSAGE >> $LOGFILE
  fi
}
#
# Check for the auto connection flag... nothing.. gone!
if [ ! -f $LOCAL/ra_connect_id ] ; then
  echo "Auto connection flag missing.  Quitting..";exit 0 ; fi

######################################################################

writelog "Auto Reflector Cleanup Active."

# see if auto-reconnect is alive
if [ -f /home/irlp/local/locked_stn ] ; then
   rm /home/irlp/local/locked_stn
   writelog "ARC - Auto-Reconnect removed"
fi

# see if DTMF has been killed, if so re-enable it
if [ -f /home/irlp/local/nodtmf ] ; then 
   rm /home/irlp/local/nodtmf
   writelog "ARC - DTMF Commands re-enabled."
fi

# see if node still active..
if [ ! -f $LOCAL/active ]; then
   rm $LOCAL/ra_connect_id
   writelog "ARC - Node no longer active"
fi

# check if auto connection still active
if [ `cat $LOCAL/active` == `cat $LOCAL/ra_connect_id` ]; then
   writelog "ARC - Disconnecting Node"
   $SCRIPT/end
   sleep 2
 else
# New connection is active, not auto setup.
   writelog "ARC - New Connection, ID Mismatch"
fi

# Check if reflect timeout was altered
#if [ -f $LOCAL/ra_oldtimeout ] ; then
#  . $LOCAL/ra_oldtimeout
#  rm $LOCAL/ra_oldtimeout
#fi

# Check if echolink needs to be re-enabled
if [ ! -f $LOCAL/echo_enable ] ; then
  /home/EchoIRLP/scripts/echo_enable
   writelog "ARC - EchoLink re-enabled."
   sleep 2
fi

# see if CWID has been killed, if so re-enable it
if [ -f /home/irlp/local/cwtimer ] ; then 
   rm /home/irlp/local/cwtimer
   /home/irlp/custom/cwtimer_mon > /dev/null 2>&1
   writelog "ARC - CW ID tone re-enabled."
fi

# kill flag file before exit!
rm $LOCAL/ra_connect_id

exit 0

