#!/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.

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

cd $VOICE_DIR

TIMESTAMP=$VOICE_DIR/incoming/.timestamp
FLAG=$VOICE_DIR/incoming/.flag

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

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

touch $TIMESTAMP-n

if [ -x $VOICE_DIR/speakdate ]; then TIME=yes; else TIME=no; fi

TMP=/tmp/vg_nmp.$$
LOCK=/tmp/vg-lock.$$

for i in $MSGS
do
	if [ $TIME = yes ]
	then
		# generate the datestamp in the background
		( touch $LOCK; $VOICE_DIR/speakdate $i >$TMP; rm $LOCK ) &
	fi

	# short beep
	$ZPLAY -S $OUT -b '[1320,0,3]'
	# play the message
	$ZPLAY -S $OUT $i

	if [ $TIME = yes ]
	then
		# wait for the datestamp to be finished
		while [ -f $LOCK ]; do sleep 1; done
		# play the datestamp
		$ZPLAY -S $OUT $TMP
		rm $TMP
	fi
done

# two long beeps
$ZPLAY -S $OUT -b '[880,0,6]'
$ZPLAY -S $OUT -b '[880,0,6]'

rm -f $FLAG $TIMESTAMP
mv $TIMESTAMP-n $TIMESTAMP
