#!/bin/sh
# you should read the instructions in incoming_fax_scripts.mk
# move or link this file to 
# /etc/mgetty+sendfax/new_fax
# ver: 19990918
#
# Originally this was a script to send mgetty's incoming faxes 
# via MIME encoded EMail; by Martin Spott (martin.spott@uni-duisburg.de)
#
# It was heavily modified by Max Klohn <amk@span.ch> 
# for simultaneous laser printing and MySQL archiving (as part of the
# freemed (http://www.freemed.org) project.
#
# This script is called when a message was recorded. 
# It gets the following arguments:
#      $1 : the hangup code
#      $2 : the remote id
#      $3 : the number of pages
#      $4... : the file names

# Place the correct EMail-adresses here !!!
USER="<fax@telecom.pmc>"
ADMIN="<root@telecom.pmc>"

# How mgetty calls us.
HANGUP_CODE="$1"
SENDER_ID="$2"
NUMBER_PAGES="$3"

# Some miscellaneous data and filenames.
TMP=/tmp
# gif scaling, set to your convenance
XSCALE=0.58
#
TIMESTAMP=`/bin/date +%Y%m%d%H%M%S`
MIME_TIFF=$TMP/TIFF_$TIMESTAMP
MIME_MAIL=$TMP/MAIL_$TIMESTAMP
SQL=$TMP/SQL_$TIMESTAMP             
ERRLOG=$TMP/SQL_ERRLOG

# The binaries we need; please check carefully !!!
BASENAME=/bin/basename
CAT=/bin/cat
CUT=/usr/bin/cut
ECHO=/bin/echo
ELM=/usr/bin/elm
G3TOPBM=/usr/bin/g32pbm
PGMTOPBM=/usr/bin/pgmtopbm
MMENCODE=/usr/bin/mmencode
PNMSCALE=/usr/bin/pnmscale
PNMTOTIFF=/usr/bin/pnmtotiff
PPMTOGIF=/usr/bin/ppmtogif
PBMTOLJ=/usr/bin/pbmtolj
RM=/bin/rm
SED=/bin/sed
SENDMAIL=/usr/sbin/sendmail
MYSQL=/usr/bin/mysql
# Set this one to where you configure freemed to find the gifs
# mine is a nfs share mounted by the fax-receiving machine 
GIFHOME=/var/package/data/fax/incoming
# SQL stuff
# Don't forget to create a user with minimal insert privileges 
# on the given table (see below for table description)
# For example:
# ------------------------------------------------
# GRANT INSERT ON freemed.infaxes to fax@localhost
# identified by 'fax' ;
# ------------------------------------------------
# If anyone has a better idea for security please feel free to improve...
# Be sure to have those right too:
SERVER=localhost
USER=fax
PASSWORD=fax
DATABASE=freemed
TABLE=infaxes
#
# Infaxes should be created by admin.php3. BTW here's the SQL if you need
# to create it from the command line:
#
# USE freemed;
# CREATE TABLE freemed.infaxes (
#    infcode	        VARCHAR(5),  
#    infsender		VARCHAR(50),
#    inftotpages		INT UNSIGNED,
#    infthispage		INT UNSIGNED,
#    inftimestamp	TIMESTAMP,
#    infimage		VARCHAR(50),
#    inforward		ENUM("no","yes") NOT NULL,		
#    infack		ENUM("no","yes") NOT NULL,
#    infptid		VARCHAR(10),
#    infphysid		VARCHAR(10),
#    id INT NOT NULL AUTO_INCREMENT,
#    PRIMARY KEY (id)
#    );
#
# Notice the hooks for a forward and a "received" ack fields, as well as
# patient id and physician id numbers (which in my opinion should be the
# official in-house numbers, and not the freemed-assigned ones
#
# This script generates gifs for freemed, mails tifs to a given user, and prints the 
# incoming faxes. You can comment out the functions you won't use.
#
# Essential lines to put into the header of a MIME mail.
HEADERLINE_1="MIME-Version: 1.0"
HEADERLINE_2="Content-Type: multipart/mixed; boundary="attachment""

# Lines to put into the header of each MIME attachment.
ATTACHMENT_HEADERLINE_1="--attachment"
ATTACHMENT_HEADERLINE_2="Content-Type: image/tiff"
ATTACHMENT_HEADERLINE_3="Content-Transfer-Encoding: base64"

# Line to close the attachment section of a MIME mail.
ATTACHMENT_ENDLINE="--attachment--"

# Now we build our MIME mailheader using commandline arguments.
$ECHO "Subject: FAX entrant de $2 avec $3 page(s)" > $MIME_MAIL
$ECHO "$HEADERLINE_1" >> $MIME_MAIL
$ECHO "$HEADERLINE_2" >> $MIME_MAIL
$ECHO "" >> $MIME_MAIL

# To handle each attachment we skip the first three arguments (those we
# already used for the header).
shift 3

# Handling of each fax page, whose names are given via commandline arguments.
# We have to cut off the absolute path via 'basename' and remove the dot
# which separates the page number. Also we add a filename extension and fit
# the result as filename into our attachment header - some mail frontends
# need this.
#
for i in $@
do
	# Let's extract the page number from the file name. Notice that
	# this will fail when the sender hasn't set the fax ID. 
	# Someone fix this...

        THISPAGE=`$BASENAME $i | $CUT -d_ -f3 | $CUT -c2-3`
	
	# Now we set the .gif filename
	
	GIFNAME=`$BASENAME $i`.gif
	
	# We use the second character in the filename to identify the
	# resolution of our incoming fax, so we can easily scale the fax for
	# display on a screen.
	
	RESOLUTION=`$BASENAME $i | $SED 's/.\(.\).*/\1/'`
	if [ "$RESOLUTION" = "n" ]
	then
		YSCALE=1.16
	else
		YSCALE=0.58
	fi
#
	# The fax is converted from G3 to PBM, it is scaled and then
	# converted to TIFF.
	# We write it into a temporary file, because 'mmencode' doesn't
	# handle standard input correctly.
	# IMPORTANT! For those who don't have Multitech modems: make damn 
	# sure to erase the -r (reverse byte order) after $G3TOPBM

	$CAT $i | $G3TOPBM -r | $PNMSCALE -xscale $XSCALE -yscale $YSCALE \
	| $PNMTOTIFF > $MIME_TIFF

	# Let's make the .gif for the database. If you don't own a Multitech
	# modem, rease the -r aftter $G3TOPBM

        $CAT $i | $G3TOPBM -r | $PNMSCALE -xscale $XSCALE -yscale $YSCALE \
        | $PPMTOGIF > $GIFHOME/$GIFNAME
	


# build the SQL command
#
$ECHO "INSERT INTO $DATABASE.$TABLE (infcode, infsender, inftotpages, infthispage, inftimestamp, infimage)" > $SQL 
$ECHO "VALUES ('$HANGUP_CODE','$SENDER_ID','$NUMBER_PAGES','$THISPAGE','$TIMESTAMP','$GIFNAME');" >> $SQL
#
# run mysql on that baby
$MYSQL -h $SERVER -u $USER -p$PASSWORD < $SQL > $ERRLOG
#
#
# printing stuff on laserjet 300 dpi
#
        if [ "$RESOLUTION" = "n" ]
           then
	$CAT $i | $G3TOPBM -r | $PNMSCALE -xscale 1.43 -yscale 2.86 | \
        $PGMTOPBM | $PBMTOLJ -resolution 300 | lpr -P${PRINTER}
           else
	$CAT $i | $G3TOPBM -r | $PNMSCALE -xysize 2479 3508 | \
        $PGMTOPBM | $PBMTOLJ -resolution 300 | lpr -P${PRINTER}
        fi
#
# end of printing stuff
#
	# Now we put the header for each attachment into our MIME mail.
	$ECHO "$ATTACHMENT_HEADERLINE_1" >> $MIME_MAIL
	$ECHO "$ATTACHMENT_HEADERLINE_2; name=\"`$BASENAME $i|cut -f1 -d\.``$BASENAME $i|cut -f2 -d \.`.TIF\"" >> $MIME_MAIL
	$ECHO "$ATTACHMENT_HEADERLINE_3" >> $MIME_MAIL
	$ECHO "" >> $MIME_MAIL
#
	# Here we do base64 encoding of out TIFF data and add the result
	# into our MIME mail as attachment.
	$MMENCODE -b $MIME_TIFF >> $MIME_MAIL
#
	# To clean up temporary TIFF data.
	$RM -f $MIME_TIFF
#
	# Each attachment has to end with a blank line (I believe).
	$ECHO "" >> $MIME_MAIL
done

# To close the attachment section of our mail.
$ECHO "$ATTACHMENT_ENDLINE" >> $MIME_MAIL

# Sending the mail.
$SENDMAIL < $MIME_MAIL $USER
#
# Run the mail queue
$SENDMAIL -q

# Cleaning up behind us (comment out if you need to debug).
$RM -f $MIME_MAIL
$RM -f $SQL 
$RM -f $ERRLOG
# That's all folks !
exit 0