#!/bin/bash

#Written by KD0WHB. Send improvements / modifications to electricity440@gmail.com
#Version 1.0

#Frequency Steering Master file
#16 Channel Radius Radio with LCD backlight
#See other script for 32 channels

#Prerequisites:
#1. Program Channel 12's name to something other than a number with 2 as the second digit. Ex. 99
#2. Feed the Bottom Right segment of the right 8-segment display to a gpio pin on the pi.
#3. Feed two GPIO pins to channel UP and Down on the radio
#4. Change permissions of this script so it is executable by running "chmod +x steer.sh"
#4. Syntax:
#steer.sh <Channel to go to 1-16> <GPIO LCD bottom right segment IN pin (Type gpio readall for pinouts)> <GPIO DOWN pin> <GPIO UP pin>
#5. Find wiringpi GPIO pinout by executing the command "gpio readall"

#Change this to the remote base node number (Needed for audio playback to node)
NODE=1004

#Change to constant numbers as needed :
CHAN=$1
UP=$2
DOWN=$3
IN=$4

#Set the pinmodes for the inputs
gpio mode $IN in
gpio mode $UP out
gpio mode $DOWN out

gpio write $UP 0
gpio write $DOWN 0

SEG=$(gpio read $IN)

asterisk -rx "rpt localplay 42622 wait-moment"

while [ "$SEG" != "0" ]
do

gpio write $UP 1
sleep .2
gpio write $UP 0
sleep .4
echo "$SEG"
SEG=$(gpio read $IN)
done

echo "passed while loop!"
#If the desired channel is equal to two, no further action is required

if [ "$CHAN" = "2" ]
then
    #nothing more to do required
    z=1 #I guess the if statement has to have some code in it
elif [ "$CHAN" = "1" ]
then
#If the channel is equal to one, simply pulse down once.
	gpio write $DOWN 1
	sleep .2
	gpio write $DOWN 0
	sleep .4
elif (($CHAN > 10)) && (($CHAN <= 16))  #In this case, it is quicker by using down arrows
then
PMARK="$(( 7 -($CHAN -10)))" #Placemark for channel steering
for (( a=1; a<=$PMARK ; a++ )) #This determines how many DOWN presses
do
	gpio write $DOWN 1
        sleep .2
        gpio write $DOWN 0
        sleep .4
done
elif (($CHAN <= 10)) && (($CHAN > 2)) #In this case it is quicker to go up
then
PMARK="$(($CHAN -2))" #Placemark for channel steering
for (( a=1; a<=$PMARK ; a++ )) #How many pulses to get to desired channel?
do
	gpio write $UP 1
	sleep .2
	gpio write $UP 0
	sleep .4
done
fi

rm -Rf /tmp/temp.ulaw
sleep 1

if (($CHAN <= 16))
then
	cat /var/lib/asterisk/sounds/channel.ulaw > /tmp/temp.ulaw
	cat /var/lib/asterisk/sounds/digits/$CHAN.ulaw >> /tmp/temp.ulaw
	asterisk -rx  "rpt playback 42622 /tmp/temp"
	echo "Channel succesfully steered to $CHAN !"
else
        asterisk -rx  "rpt playback 42622 option-is-invalid"
fi
