#!/bin/bash
#
# This script is run from crontab, and will play a warning at 10 minutes before connection
# and then again at 5 minutes before connection to the reflector.  After the connection
# has been made, it monitors activity and disconnects after the activity timeout period
# if no COS has been detected locally (This is here because of some issues found with
# the default COS activity timeout function)
#
# V1.0 15/02/03 - Geoff VK2XJG
# V1.1 16/03/03 - Geoff VK2XJG - added 5 mins worth of coscheck in 3 places to stop node
#                 keying over people already in QSO
# V3.0 15/04/03 - Geoff VK2XJG - Defined config file to allow multiple instances of script to
#                 exist without problems
# V3.1 27/04/03 - Geoff VK2XJG - New features added: Reflect_timeout Override and Force
#                 Disconnection of active link if set in config file
# V3.2
# V3.3
# V3.4
# V3.5
# V3.6 21/02/04 - Geoff VK2XJG - Added support for a PTT_RESET flag to drop PTT regularly for broadcast streams
# V3.7 22/08/08 - Steve VK8SJ  - Touchups to logging, CentOS, dummy-spits and kill CWid
#                                also added flag to send confirmation tones if activated from custom-decode
#                                Add test for warning files existance - allows
#                                config file to set 'none' if no warnings req'd.
# V3.8 12/09/08 - Steve VK8SJ  - Added flags to enable kill script as timeout
#                                value tends to wander - use with 'notimeout'
#                                and disconnect with reflect_auto_kill in cron
# V4.0 25/04/10 - Steve VK8SJ  - Modified again to use standard connect script as
#                                this copy is toooo old(?) and has security issues
#                                with echoIRLP reflectors..
# V4.1 26/04/10 - Steve VK8SJ  - Reflector timeout routine fixed
#
######################################################################
#
# Make sure we are user repeater!!!
   if [ "`/usr/bin/whoami`" != "repeater" ] ; then
     echo "This program must be run as user REPEATER!"
     exit 1
   fi
# Make sure we have sourced the environment file
   if [ "$RUN_ENV" != "TRUE" ] ; then
      . /home/irlp/custom/environment
   fi

#############################################################################
############################# Functions #####################################
#############################################################################
#
### writelog
# This function logs Date etc then message..
#
function writelog () {
  MESSAGE="`date '+%b %d %Y %T'` "$@
  if [ -n "$LOGFILE" ]; then
    echo $MESSAGE >> $LOGFILE
  fi
}
#
### Key...
#
function my_key () {
      $BIN/coscheck
      $BIN/coscheck
      $BIN/coscheck
      $BIN/coscheck
      $BIN/coscheck
      $BIN/coscheck
      $BIN/coscheck
      $BIN/coscheck
      $BIN/coscheck
      $BIN/coscheck
      $BIN/key
}
#
### Send Tone
# Key the PTT, wait for a while (specified amount of time below),
# play the confirmation beep-beep wav file, then unkey the PTT
#
function sendtone () {
   my_key
   sleep .5
   $BIN/play $AUDIO/custom/sound-confirm.wav     # contains 'beep beep' or whatever
   sleep .5
   $BIN/unkey
}
#
######################################################################
####################################################################
#
#
echo "Reflector Auto Connect Script."
if [ ! -f $LOCAL/enable ] ; then
   echo "ERROR - Node disabled! .. exiting."
   writelog "${0##*/}: ERROR - Node Disabled! .. exiting"
   echo
   exit 0
fi

CONFIG_FILE=$1

# If no config file has been defined, exit.
if test -z $1 ; then
  echo "You must specify a config file!"
  exit 1
fi

# Read in the specified config file
. $CUSTOM/$CONFIG_FILE
echo -n "Using configuration - "$CONFIG_FILE

writelog "Auto Reflector Connect Activated, "$CONFIG_FILE

if [ ! "$CONF_TONES" = "NO" ] ; then
   sendtone            #sends 'beep-beep' confirmation of command accepted
   sleep 2
fi
echo
echo "Starting countdown"
timer=$COUNTDOWN
X=0
PRE=TRUE

while [ "$PRE" = "TRUE" ] ; do
  if [ $timer = $COUNTDOWN ] ; then
    if $BIN/pttstate ; then
      if $BIN/cosstate ; then
        echo "No COS detected, Play first warning..."
        $BIN/coscheck
        $BIN/coscheck
        $BIN/coscheck
        $BIN/coscheck
        $BIN/coscheck
        $BIN/coscheck
        $BIN/coscheck
        $BIN/coscheck
        $BIN/coscheck
        $BIN/coscheck
        if [ -f $WARNING_1_FILE ] ; then
          $BIN/key
          usleep 50000
          $BIN/play $WARNING_1_FILE
          $BIN/unkey
        else
          echo "No 1st warning file specified."
        fi
        X=1
      else
        echo "COS is active. Reset timer."
        timer=$COUNTDOWN
      fi
    else
      echo "PTT is active. Reset timer."
      timer=$COUNTDOWN
    fi
  fi

  if [ $X = 1 ] ; then
    let timer=$timer-1
  fi
  echo -ne "    \r"$timer"\r"
  # If the countdown has reached the value of WARNING_2, play the warning.
  #
  if [ $timer = $WARNING_2 ] ; then
    if $BIN/pttstate ; then
      $BIN/coscheck
      $BIN/coscheck
      $BIN/coscheck
      $BIN/coscheck
      $BIN/coscheck
      $BIN/coscheck
      $BIN/coscheck
      $BIN/coscheck
      $BIN/coscheck
      $BIN/coscheck
      if [ -f $WARNING_2_FILE ] ; then
        echo "No COS detected, Play second warning..."
        $BIN/key
        usleep 50000
        $BIN/play $WARNING_2_FILE
        $BIN/unkey
      else
        echo "No 2nd warning file specified."
      fi
    else
      echo "PTT is active. Skip second warning."
    fi
  fi

  # Check if the timer has reached 0 yet...
  #
  if [ $timer = 0 ] ; then
    # If we are connected somewhere already, do nothing,
    # otherwise connect to reflector
    #
    if [ -f "$LOCAL"/active ] ; then
      if [ "$FORCE_DISCONNECT" = "NO" ] ; then
        writelog "Auto Reflector Connect ABORTED, A link is active"
        echo "Times up, but connected, so aborting."
        exit 1
      else
        writelog "Auto Reflector Connect - Bringing down active link"
        echo "Times up, bringing down active link so we can connect"
        $SCRIPT/end
        sleep 3
      fi
    fi
#
#    # If the TIMEOUT_VALUE needs to be overridden, we do this here.
#    # In the case of NOTIMEOUT, we set the timeout to 12hrs (36000 seconds).
##
#### This doesn't work with the 'standard' connect script...
#### We need to change the timeout environment variable directly
##
#     if [ "$OVERRIDE_DEFAULT_TO" = "YES" ] ; then
#       if [ "$AUTO_TIMEOUT" = "NOTIMEOUT" ] ; then
#         AUTO_TIMEOUT=36000
#       fi
#       export REFLECT_TIMEOUT_VALUE=$AUTO_TIMEOUT
#       grep REFLECT_TIMEOUT_VALUE $CUSTOM/environment > $LOCAL/ra_oldtimeout
#     fi
#
    echo "Current Timeout is set to "$REFLECT_TIMEOUT_VALUE

    echo "Time's up! Lets get going..."

# Stop the Echolink node for the broadcast
    if [ ! "$ECHO" = "NO" ] ; then
      echo "Stopping EchoIRLP engine"
      /home/EchoIRLP/scripts/echo_disable
    fi

    $BIN/coscheck
    $BIN/coscheck
    $BIN/coscheck
    $BIN/coscheck
    $BIN/coscheck
    $BIN/coscheck
    $BIN/coscheck
    $BIN/coscheck
    $BIN/coscheck
    echo "No COS detected, lets connect to the reflector..."

############################################################
##  Modification 93z, again, hmmm.....
# Stop dtmf controls
    touch $LOCAL/nodtmf
    $SCRIPT/connect_to_reflector $REFLECTOR
# Added for disconnect comparison in reflect_auto_kill
    cp $LOCAL/active $LOCAL/ra_connect_id
# Check for, and kill CW Ident generator if needed
    if [ $ID_KILL != "NO" ] ; then
       touch /home/irlp/local/cwtimer
       echo "CW ID Generator disabled"
    fi
#
###########################################################
    PRE=FALSE
    if [ "$PTT_RESET" = "YES" ] ; then
      echo -n "Starting PTT RESET script... "
      $CUSTOM/ptt_reset >/dev/null &
      echo "done ..."
    fi
  fi

  sleep 1

done
echo
exit 0
