#!/bin/bash
#########################################################################################
#
# filename:  txfan
#
# description:  This file controls a PC fan attached to any aux port.  It starts up when
#   PTT is detected, and will stay on for the time period specified in
#   the TIMEAFTER variable after the PTT drops.  If the PTT is triggered
#   in the countdown period, the timer resets.
#
# original authors:     Thanks to KC6HUR, WW4M, N8DNX, NE1H for building the state manager framework, that
#   this script uses.
#
#   Add the following code snipit near the end of rc.irlp.
#   This will restart the cos_watch process each time the
#   node is restarted.
#
#   if [ -f ${CUSTOM}/txfan ] ; then
#     echo -n "Starting TXFAN process..."
#     killall txfan &>/dev/null
#     /bin/su - -c ${CUSTOM}/txfan repeater &>/dev/null &
#     echo "done!"
#   fi
#
# history:
# 2005-02-16    kd6hwc  Initial creation (with help from other scripts)
#########################################################################################

# Define the AUX Switch that the fan is connected to
AUXPORT=3

# Define the period of time after the PTT drops to shut off the fan
TIMEAFTER=300

# define variables
declare -i IDLETIMER

# need to set environment
. /home/irlp/custom/environment

# Make sure we are user repeater!!!
if [ `/usr/bin/whoami` != "repeater" ] ;
then
 echo This program must be run as user REPEATER!
 exit 1
fi

# Start with state set to "Initial"

STATE="Initial"

while [ TRUE ]
do

case "$STATE" in


 "Initial")      # Wait for first keyup, then proceed to Countdown

  echo -en "\n\n"`date ` "STATE = Initial\n"

  # while IRLP board is silent (PTT=T)
  while $BIN/pttstate ; do
   sleep 1
  done

  echo -en "\nPTT keyed, activating fan"
  ${BIN}/aux"$AUXPORT"on
  STATE="Countdown"
 ;;


        "Countdown")      # Count down period, if PTT is triggered, reset the timer.

                echo -en "\n\n"`date ` "STATE = Countdown\n"
                sleep 1
                IDLETIMER=$TIMEAFTER

                while [ TRUE ]
                do
                        echo -en "\rWaiting for Countdown: $IDLETIMER    "
                        IDLETIMER=$IDLETIMER-1
                        sleep 1

   if ! $BIN/pttstate
                        then
     IDLETIMER=$TIMEAFTER
   fi

                        if [ $IDLETIMER = 0 ]
                        then
                                break
                        fi
  done

  echo -en "\nTimer expired, deactivating fan"
  ${BIN}/aux"$AUXPORT"off
  STATE=Initial
 ;;

 esac
done

echo -e "\n\nOops! - Not supposed to get to here"

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