#!/bin/bash
#
# This script is Free Software (as in beer)
# You may do whatever you want with it as long as you keep
# the author's credits:
#
# Martin Rode, Programmfabrik GmbH, www.programmfabrik.de
#
# The script takes one argument from the samba server
#
#
# Call Samba like this:
#
# [faxprinter] 
#         print command = /smbhome/pdfprinter/faxscript %s
#         path = /smbhome/pdfprinter
#         printable = yes         
#         comment = Treiber: Minolta Color PageWorks/Pro PS
#
#

# whats the keyword for the faxnumber?
FAXPHRASE='PER-FAX-AN'

# the email domain which will be added to the user (see below)
DOMAIN="zeroscale.com"

LOGFILE="/tmp/faxlog"

# find the file name
FILE=$(egrep "^%%Title:" "$1" | head -n 1 | sed -e 's/^%%Title: //g' | sed -e 's/^(//g' | sed -e 's/\(.*\)\..*$/\1/g' | tr -d "\r\n")
FILE=`echo -n -e $FILE`

# find the user's name
USER=$(egrep "^%%For:" "$1" | head -n 1 | sed 's/^%%For: //g' | tr -d "\r\n")

# remove crap from the beginning and end of the ps file
POS_S=`egrep -n "^%\!PS-Adobe" "$1" | cut -d : -f 1 `
POS_E=`egrep -n "^%%EOF" "$1" | cut -d : -f 1`
sed 1,$[$POS_S - 1]d "$1" | head -n $[$POS_E - $POS_S + 1] > "${FILE}.ps" 

# now we can remove the smb file
rm -f "$1"

# first generate a txt
OPTIONS="-q -dNODISPLAY -dSAFER -dNOBIND -dWRITESYSTEMDICT -dSIMPLE"
				gs $OPTIONS -c save -f ps2ascii.ps "${FILE}.ps" >"${FILE}.txt" 

# find the number
NUMBER=$(egrep -i "$FAXPHRASE" "${FILE}.txt" | perl -e "\$line=<stdin>; \$line=~ /$FAXPHRASE([0-9\-\. ]+)/i; print \$1;" | tr -d "[:punct:][:space:]")

# textfileno longer needed, kill it
rm -f "${FILE}.txt"

if [ $NUMBER ]; then  
		SUBMIT=`sendfax -D -f "${USER}@${DOMAIN}" -n -m -d "$NUMBER" "${FILE}.ps"`

		MSG="\n`date`\nFax submitted: '$SUBMIT'\nTO: '$NUMBER'\nFILE: '$FILE'\nUSER: ${USER}@${DOMAIN}"

		echo -e "$MSG" | mail -s "Fax submitted!" ${USER}@${DOMAIN}
else
		MSG="\n`date`\nNo Number recognized in your document!\nMake sure you have the keyword '${FAXPHRASE}' in it\nFILE: '${FILE}'\nUSER: ${USER}@${DOMAIN}"

		echo -e "$MSG" | mail -s "No Number recognized!" ${USER}@${DOMAIN}
fi

echo -e "$MSG" >> $LOGFILE

# if you want to remove the .ps file as well, do it here
rm -f "${FILE}.ps"
