#!/bin/bash
#
# fax conversion script for the efax package:
#   called by /usr/bin/fax when a fax is received.  Convert it to a
#   multipage compressed postscript document and e-mail it to $MAILTO
#   (default is postmaster)
#
# Copyright 1998, 1999 by Avery Pennarun <apenwarr@worldvisions.ca>
# Use, modify, and redistribute freely.
#

SENDMAIL=/usr/sbin/sendmail
FAXMGR=root
FAXDIR=/var/spool/fax

# override all options from the efax config file
source /etc/efax.rc

# process the command line
REMID="$(echo "$1" | sed 's/\(^\| \) */\1/g')"
shift
FILES="$*"

#set -x

xmit()
{
    SUBJECT="$1"

    (
	cat <<-EOF
		From: <efax@$HOSTNAME>
		MIME-Version: 1.0
		Subject: $SUBJECT
		Content-Type: multipart/mixed; boundary="xyz"
		Content-Transfer-Encoding: 7bit
		
		This is a MIME encoded message.  Use a MIME-compatible e-mail
		package if you want to read it.
		
		EOF

	cat <<-EOF
		--xyz
		Content-Type: application/postscript; name="fax.ps.gz"
		Content-Disposition: attachment; filename="$(basename fax.ps.gz)"
		Content-Transfer-Encoding: base64
		
		EOF
	
	shift
	cat | gzip -c | mimencode
	
	echo "--xyz"
	
    ) | $SENDMAIL $FAXMGR
}

set -e

cd $FAXDIR

PAGES="$(echo $FILES | wc -w | sed 's/[ 	]*//g')"

echo "Processing fax from $REMID ($PAGES pages)"
efix -ops $FILES </dev/null 2>/dev/null \
	| xmit "Fax: $PAGES pages from "\""$REMID"\"
mkdir done 2>/dev/null || true
mv $FILES done/ 2>/dev/null || true
