#!/bin/sh
#
# this one dequeues the messages from where they're spooling and
# moves them over to the PC.

cd /var/spool/fax

# following stuffed in to prevent more than one of these running at a
# time 
# Note that shlock compares
# pids so it doesn't matter if a process dies and leaves a lock sitting
#		- Brian

if /usr/lib/news/shlock -p $$ -f FAXLOCK ; then
	:
else
	echo ${pname}: "[$$]" already running "[`cat FAXLOCK`]"
	exit 0
fi

nfiles=`find . -name '*.q*' -print | wc -l`
if [ $nfiles = "0" ] ; then
	rm FAXLOCK
	exit 0;
fi


# zap commands left over from last time
rm queue.bat

# following grabs all the error files from the last go-round,
/usr/local/bin/kermit << EOF
set line /dev/tty0d
set baud 9600
get f*.err
quit
EOF

# analyze the .err files we got, and add the appropriate
# deletes to the outgoing batch file.  Successful faxes get deleted
# from the current spool directory here too; unsuccessful ones get
# requeued

for f in *.err ; do
	if [ ! -r $f ] ; then
		continue;
	fi
	fb=`basename $f .err`
	echo $f $fb ;

	# we got the errors file, blow it away on the PC
	echo "DEL $f" >> queue.bat ;

	# see if it was sent ok
	if ( egrep -i 'Sent successfully' $f ) ; then
		rm $fb.* ;
		continue ;
	fi

	# see if it failed miserably
	if ( egrep -i 'error' $f ) ; then
		frm=`egrep From: $fb.txt | sed -e 's/From: //'` ;
		more FAXERR $fb.* | Mail -s "Fax mail error" $frm brian ;
		rm $fb.* ;
		continue ;
	fi;

	# otherwise, requeue and remove the errors file
	cat $fb.q.o >> queue.bat ;
	rm $f ;
done

# cat all the new queue files onto the batch file
nq=`find . -name '*.q' -print | wc -l`
if [ $nq -gt 0 ] ; then
	for f in *.q ; do
		cat $f >> queue.bat ;
		mv $f $f.o ;
	done ;

	# ship over the current text files
	/usr/local/bin/kermit << EOF
set line /dev/tty0d
set baud 9600
send f*.txt
quit
EOF
fi

# make sure that the last thing in the batch restarts the PC script
echo "AUTOFAX" >> queue.bat

# ship over batch list of things to do
# 'finish' makes the PC kermit exit and execute the queue.bat file
# we just delivered
/usr/local/bin/kermit << EOF
set line /dev/tty0d
set baud 9600
send queue.bat
finish
quit
EOF

echo "===================================================" >> /var/log/fax
date >> /var/log/fax
cat queue.bat >> /var/log/fax
rm -f  FAXLOCK
exit 0
