#!/bin/sh

# This shell script gets called by vgetty if a DTMF
# command is detected, the digits heard are passed
# in $1 (not including the leading * and trailing #).
#
# If a digit was typed during playback of the greeting
# message, it is treated as a 1-digit DTMF command string.

VOICE_DIR=/var/spool/voice
ZPLAY=/usr/bin/zplay

PATH=$VOICE_DIR:/bin:/usr/bin:/usr/local/bin

### debugging commands ###
DEBUG=false
EXEC=exec
if [ "$DEBUG" = true ]; then ZPLAY=zplay_sim; EXEC=exec_sim; fi
zplay_sim () { echo -n $* " : " >/dev/stderr; read q; echo $q; }
exec_sim () { echo $*; exit 0; }

### useful subroutines to help handle caller hangups
# play a voice file, read dtmf digit(s) and store it in $dtmf,
# quit if the hanger hangs up

Get_dtmf_command () {
	if [ ! -f $1 ]; then msg=$VOICE_DIR/messages/beep; else msg=$1; fi
	dtmf=`$ZPLAY -St -C $msg`
	if [ $? = 2 ]; then exit 0; fi
}

Get_dtmf_digit () {
	if [ ! -f $1 ]; then msg=$VOICE_DIR/messages/beep; else msg=$1; fi
	dtmf=`$ZPLAY -St -D $msg`
	if [ $? = 2 ]; then exit 0; fi
}

### 
# Play the new messages if the code is correct.
# Required: a file called .code containing an ascii number,
# and the following voice files in the message directory.

CODE=`cat $VOICE_DIR/.code`
MSG_DIR=$VOICE_DIR/messages

M_GET_CODE=$MSG_DIR/get-code
M_INCORRECT=$MSG_DIR/incorrect
M_GOODBYE=$MSG_DIR/goodbye

MAXTRIES=3
TRIES=0

Check_code () {
	case $1 in
	"$CODE")
		# play back the new messages and quit
		$EXEC vg_nmp "telco" ;;
	*)
		$ZPLAY -St $M_INCORRECT	;;
	esac
}


# Allow three tries to get the correct code

dtmf="$1"

while [ $TRIES -lt $MAXTRIES ]
do
	# if there were several digits passed to vg_dtmf,
	# treat them as the first input,
	# otherwise get the code now.
	if [ $TRIES -gt 0 -o -z "$dtmf" ]
	then
		Get_dtmf_command $M_GET_CODE
	fi
	case "$dtmf" in
	?) Get_dtmf_command $M_GET_CODE ;;
	*) ;;
	esac

	Check_code $dtmf

	TRIES=`expr $TRIES + 1`
done

$ZPLAY -St $M_GOODBYE

exit 0
