#!/bin/sh
# 
# Modified fax SERVER script for use with Xfax (K. Lemmens)
# Original Copyright 1993-1996 by Ed Casas 
# 
# --- Start of user configuration section --- 
# 
# Note: do not put spaces before or after the equal (=) signs.
#

# The names of the fax script, efax and efix including full path
# if necessary.

XFAX=/opt/lib/xfax
EFAX=$XFAX/efax

SPOOLDIR=/var/spool/fax
MAXTRY=6

# The device to which the fax modem is connected (e.g. ttya for
# /dev/ttya).  Use a dial-out (cua) device if available.  If
# there are links to this device then all programs must use same
# name or the UUCP locking mechanism will fail.  For example, if
# /dev/modem is a link to /dev/cua1, then getty, uucp, kermit,
# pppd, dip, etc. must *all* use either /dev/modem or /dev/cua1.

DEV=cua1

# The type of fax modem commands to use.  Un-comment one of the
# following lines depending on your modem.

# CLASS=1
CLASS=2
# CLASS=2.0

# Your fax number in international format, 20 characters maximum.
# Use only digits, spaces, and the "+" character.

FROM="+31 15 1111111"

# Your name as it should appear on the page header.

NAME="Unknown"

DIALPREFIX="T"
DIALSUFFIX=""

# The name(s) of lock file(s) according to your system's
# conventions. Protect with single quotes for delayed evaluation.
# Add a leading '#' to the file name to use HDB (ASCII) format.

LOCK='-x /usr/spool/uucp/LCK..$DEV'		# "normal" systems
# LOCK=''					# no lock file
# LOCK='-x /usr/spool/locks/LK.047.040.011'	# SysV style names
# LOCK='-x #/usr/spool/uucp/LCK..$DEV'		# HDB format (ASCII pid)
# LOCK='-x /usr/spool/uucp/LCK/LCK..$DEV'	# NeXT

# Uncomment one of the following lines to force xon/xoff flow
# control if you have one of the types of modems listed.  

# FCINIT='-j\Q4'		# AT&T (Dataport, Paradyne)
# FCINIT='-j\Q1'		# Motorola (Power Modem, 3400 Pro,...)
# FCINIT='-j*F1'		# QuickComm (Spirit II)
# FCINIT='-j&H2'		# USR (Courier, Sportster)

# ****************************************************************
# The remaining options probably won't need to be changed.
# ****************************************************************


# Commands to set up modem.  "-iZ -i&FE&D2S7=120 -i&C0"
# works with almost all modems.  See the efax(1) man page for
# details.

#INIT="-iZ -i&FE0Q0V1X4&D2S7=120 -i&C0" # for efax 07a
INIT="-iZ -i&FE&D2S7=120 -i&C0"        # for efax 08a

# Command(s) to reset modem when efax finishes. "-kZ" works in
# almost all cases.

#RESET="-zZ"  # for efax 07a
RESET="-kZ" # for efax 08a
# RESET="-kZ -k&F+FCLASS=0"	# for modems that stay in fax mode after reset

# Speaker mode(M) and loudness(L). Mn sets speaker mode where n
# means: 0:never, 1:until carrier, 2:always, 3:on receive only.

SPKR="-iM1L0"

# Options for different command sets.  Normally -o1 for Class 1,
# none for Class 2 and -o0 for Class 2.0.

CLASS1INIT="-o1"	# Class 1
#CLASS2INIT="-i+FCLASS=2 -i+FCR=1 -or" # for efax 07a
CLASS2INIT=""		# Class 2     # for efax 08a
CLASS20INIT="-o0"	# Class 2.0

# The modem's capabilities for sending faxes.  "1,3,0,0,0,0,0,0"
# should almost always work. The second digit can be 5 for a
# 14,400 bps fax modem.  See the efax(1) man page for a
# description of the fields.

TXCAP="1,3,0,0,0,0,0,0"

# Additional options required only for transmit or only for
# receive.  None normally required.

TXINIT=""

# Command to make a date for the page header. Protect with single
# quotes.  'date "+%y/%m/%d %H:%M"' works on most systems.

DATECMD='date "+%y/%m/%d %H:%M"'	# YY/MM/DD HH:MM (24hour)
# DATECMD='date'			# longer, more readable

# Page header format.  You may use $DATE, $NAME, $FROM, $TO, and
# "%d/%d" (for page number and count).  Protect with single
# quotes.  Example: '$DATE $NAME ($FROM) --> $TO p. %d/%d'.

HDR='$DATE  $NAME ($FROM)  -->  $TO  p. %d/%d'

# BUSYRETRIES is a list of delays in seconds between attempts to
# redial busy numbers.  Comment out if you don't want to retry
# busy numbers.

BUSYRETRIES="30 60 120 300"
#BUSYRETRIES="30"

# Command to run another program (efax) at a higher-than-normal
# scheduling priority.  This command isn't used if it fails
# (e.g. because the current user isn't privileged).  Comment this
# out if it causes problems.

NICE="nice -n -10"

# Types of messages to display.  VERB sets the messages displayed
# and VERBLOG the messages written to log files.

VERB="ewin"		# show errors, warnings, progress & negotiation
VERBLOG="chewmainrxtf"	# log everything


# ****************************************************************
# --- End of user configuration section ---
# ****************************************************************


# --- set any variables given on command line

while : ; do
	case $# in 0) break ;; esac
	case "$1" in [A-Z]*=*) eval $1 ; shift ;; *) break ;; esac
done

# -------- initialize 

ERR=0

$NICE true 2>/dev/null ; case $? in 0) ;; *) NICE="" ;; esac

# -------- resolve dependencies on command-line arguments

eval LOCK=\"$LOCK\"			# depends on DEV

# make device name w/o directories

case $DEV in
	*/*) DEVN=`echo $DEV|sed -e s./._.g` ;;
	*) DEVN=$DEV ;;
esac

case $CLASS in
	2.0) 	CLASSINIT="$CLASS20INIT" ;;	# Class 2.0
	2)   	CLASSINIT="$CLASS2INIT"	 ;;	# Class 2
	1)   	CLASSINIT="$CLASS1INIT"	 ;;	# Class 1
	*)   	echo "Error: CLASS=\"${CLASS}\" not valid."  ; exit 2 ;;
esac

# fax send : fax files to given number

for FAX in `ls $SPOOLDIR/ `; do
  BASEDIR=$SPOOLDIR/$FAX

  if [ -r $BASEDIR/faxinfo ]; then

     while : ; do    # so we can use `break' to get to the end of the script

	case "$TO" in '') TO="$TELNO" ;; *) ;; esac
	
	TELNO=`grep "FaxNumber:" $BASEDIR/faxinfo | sed -e 's/FaxNumber://'`
	TELNO=`echo $TELNO|sed "s/[ 	()][ 	()]*//g"`

	case $TELNO in 
	'') 	;; 
	*)	TELNO="${DIALPREFIX}${TELNO}${DIALSUFFIX}" ;; 
	esac
	
	EMAIL=`grep "EmailAddress:" $BASEDIR/faxinfo | sed -e 's/EmailAddress://' `
	
	FILES=""
		if [ -r $BASEDIR/frontpage.g3.001 ]; then
		FILES="$FILES $BASEDIR/frontpage.g3.001"
	fi
		if [ -r $BASEDIR/g3fax_0001.001 ]; then
		FILES="$FILES $BASEDIR/g3fax_*"
	fi
	
	# check that all files are OK

	for f in $FILES ; do
		case $f in -) continue ;; esac
		if [ ! -r $f ] ; then
	      		echo "can't read file $f" ; ERR=2 ; break 2 
   	   	fi
	done # filecheck

	# send it

	echo Now processsing directory: $BASEDIR from $EMAIL ...
	
	logfile=$BASEDIR/`date +%m%d%H%M%S`.log
	statfile=$BASEDIR/`date +%m%d%H%M%S`.stat

	for t in 0 $BUSYRETRIES ; do

		case $t in 
		0) ;; *) echo "Will try again in $t seconds" ; sleep $t ;;
		esac

		DATE=`eval "$DATECMD"`
		eval HDR=\"$HDR\"
		
		echo | tee -a $logfile
		
		($NICE $EFAX -v "$VERB" \
		-d/dev/$DEV $LOCK $INIT $SPKR \
		$CLASSINIT $FCINIT $TXINIT \
		-c "$TXCAP" -l "$FROM" $RESET -h "$HDR" \
		-t "$TELNO" $FILES 2>&1; echo $? > $statfile) | tee -a $logfile

		ERR=`cat $statfile`
		echo "Status: $ERR"
		
		echo | tee -a $logfile
		case $ERR in
		0)	echo "Fax from $EMAIL delivered succesfully to $TELNO" |\
			  tee -a $logfile
			break 2 ;;
		1)	echo "$TELNO currently busy" | tee -a $logfile
			;;
		*)	echo "There were errors (see ${logfile})." | tee -a $logfile
			;; # retry just as with busy
		esac
	done # busyretries
	break
    done # endless while loop
    
    # Send logfile by email if requested:
    # "Debug" will send an email after every attempt,
    # "True" only if attempt was succesful.
    
    if grep "Email: Debug" $BASEDIR/faxinfo >/dev/null; then
    	mailx -s faxmessage $EMAIL < $logfile
    fi
    
    # Next routine removes a fax if it couldn't be sent for more than
    # MAXTRY times and then mails the user a warning.
    
    TRYCOUNT=`ls $BASEDIR/*.log | wc -l`
    if [ $TRYCOUNT -gt $MAXTRY -a $ERR -ne 0 ]; then
	echo | tee -a $logfile
	echo "Fax from $EMAIL failed: too many retries ($MAXTRY)" |tee -a $logfile 
	echo "Please check the faxnumber ($TELNO) and try again." |tee -a $logfile 
	echo "All faxfiles are available in $BASEDIR on your server." |tee -a $logfile 
        mailx -s "fax failed" root < $logfile	
        mailx -s "fax failed" $EMAIL < $logfile	
	mv $BASEDIR/faxinfo $BASEDIR/failinfo
    fi

    # remove faxdir if delivery was succesfull
    if  [ $ERR -eq 0 ]; then
       if grep "Email: True" $BASEDIR/faxinfo >/dev/null; then
  	  mailx -s faxmessage $EMAIL < $logfile
       fi
       rm -rf $BASEDIR
    fi
  fi  # only if faxinfo exists
done
