#! /bin/sh

# This program is intended to be called via vgetty, not
# interactively.

# play new messages, update flag and timestamp.
# If there are no new messages, play all the old ones.

# The variable below should be set by the Makefile.
# If you see three '@'s, the `make install' didn't work.
VOICE_DIR=@@@VDIR@@@

cd $VOICE_DIR

PATH=/bin:/usr/bin:/usr/local/bin:$VOICE_DIR
TIMESTAMP=$VOICEDIR/.timestamp

if [ "$1" = "speaker" ]
then
	OUT=-s
else
	OUT=-t
fi

if [ ! -f $TIMESTAMP ]
then
	MSGS=`find incoming -type f -print`
else
	MSGS=`find incoming -type f -newer $TIMESTAMP -print`
	if [ -z "$MSGS" ]
	then
		# play all of them
		MSGS=`find incoming -type f -print`
	fi
fi

touch $TIMESTAMP-n

if [ -x $VOICE_DIR/speakdate ]
then
	TMP=/tmp/vg_nmp.$$
	LOCK=/tmp/vg-lock.$$

	for i in $MSGS
	do
		( touch $LOCK; speakdate $i >$TMP; rm $LOCK ) &
		# short beep
		zplay -S $OUT -b '[1320,0,3]'
		# play the message
		zplay -S $OUT $i
		# wait for the datestamp to be finished
		while [ -f $LOCK ]; do sleep 1; done
		# play the datestamp
		zplay -S $OUT $TMP
		rm $TMP
	done
else
	for i in $MSGS
	do
		# short beep
		zplay -S $OUT -b '[1320,0,3]'
		# play the message
		zplay -S $OUT $i
	done
fi

# long beep
zplay -S $OUT -b '[880,0,6]'
zplay -S $OUT -b '[880,0,6]'

rm -f .flag
mv $TIMESTAMP-n $TIMESTAMP
