#! /bin/bash

SENDMAIL=/usr/sbin/sendmail
AWK=/usr/bin/gawk
INFO=/usr/sbin/faxinfo
FAX2PS=/usr/bin/fax2ps

#
# faxrcvd qfile time protocol sigrate error-msg [devID]
#
if test $# != 5 -a $# != 6
then
    echo "Usage: $0 qfile time sigrate protocol error-msg [devID]"
    exit 1
fi
FILE="$1"
TIME="$2"
RATE="$3"
FORMAT="$4"
MSG="$5"
DEVICE="${6:-Unspecified Device}"

###################################################################
######################### NEW by MHA ##############################
# filenames need to be unique, but they aren't, when we move
# files from the recvq-dir to the user directories;
# that's why I added a timestamp, now they _are_ unique
# (hylafax reuses the name if the file doesn't exist in 'recvq',
#  but in fact a file with that name might still exist in one of
#  the faxusers directories)
t=`date +%s`
mv /var/spool/fax/$FILE /var/spool/fax/${FILE}$t
FILE=${FILE}$t

# create flag-file, that tells 'faxconvert' that
# there's a new fax and the name of the new fax-file
echo $MSG >/var/spool/fax/recvq/newfax-`echo $FILE | $AWK -F/ '{ print $NF }'`

# start conversion (done by the other machine, if done locally,
#                   insert 'faxconvert' instead)
telnet chws01.chemnitz.debis-sfi.de 11111 >&/dev/null
######################### END MHA #################################
###################################################################

#
# Check the sender's TSI and setup to dispatch
# facsimile received from well-known senders.
#
SENDER="`$INFO $FILE | $AWK -F: '/Sender/ { print $2 }' 2>/dev/null`"
SENDTO=
if [ -f etc/FaxDispatch ]; then
    . etc/FaxDispatch	# NB: FaxDispatch should use $SENDER to set $SENDTO
fi

Notify()
{
    echo "To: $*"
    echo "From: HylaFAX <fax>"
    echo "Subject: Fax empfangen von $SENDER";
    echo "";
    $INFO $FILE
    cat<<EOF
TimeToRecv: $TIME Minuten
SignalRate: $RATE
DataFormat: $FORMAT
ReceivedOn: $DEVICE
EOF
    if [ "$MSG" ]; then
	echo ""
	echo "Das ganze Dokument wurde nicht empfangen wegen:"
	echo ""
	echo "    $MSG"
    fi
}

(Notify FaxMaster
if [ -n "$SENDTO" ]; then
    echo ""
    echo "The facsimile was automatically dispatched to: $SENDTO." 
fi
) | 2>&1 $SENDMAIL -ffax -oi FaxMaster
if [ -n "$SENDTO" ]; then
    (MIMEBOUNDARY="NextPart$$"
     echo "Mime-Version: 1.0"
     echo "Content-Type: Multipart/Mixed; Boundary=\"$MIMEBOUNDARY\""
     echo "Content-Transfer-Encoding: 7bit"
     Notify $SENDTO
     echo ""
     echo "--$MIMEBOUNDARY"
     echo "Content-Type: application/postscript"
     echo "Content-Description: FAX document"
     echo "Content-Transfer-Encoding: 7bit"
     echo ""
     $FAX2PS $FILE 2>/dev/null
     echo ""
     echo "--$MIMEBOUNDARY--"
    ) | 2>&1 $SENDMAIL -ffax -oi $SENDTO
fi

