#!/bin/sh
# 
#     Faxing with HylaFax through a faxprinter
#     Faxing with Mgetty  through a faxprinter
# 
# This script is heavily depending (just about copied) from the work of:
#     -------------------------------------------------
#     Faxfilter für MS-Windows und lpd und mgetty-paket
#     Author     : Wundrig Roland     
#     -------------------------------------------------
# The intellectual (c) remains with Roland Wundrig
# This rev created by ignace.suy@purpel3.nl, september 2000
# Developed and tested using Hylafax 4.1beta2 On SuSE 6.4.
#

set -x

LOG=/tmp/log_$$
echo "date `date`" > $LOG


# constants
SENDMAIL="/usr/sbin/sendmail"

# make up a temporary file
FAXFILE=/tmp/$1    # fax file
FAXLIST1=/tmp		# number fax list
Err_Faxspool=/tmp/Err_$$
Msg_Faxspool=/tmp/Msg_$$

# directory for enreg fax file
FAXFILE_FIN=/tmp

# pgm envoi de fax mgetty
#faxspool="/usr/bin/faxspool"
# pgm envoi de fax hylafax
sendfax="/usr/bin/sendfax"

toto1=$1
toto2=$2
toto3=$3
toto4=$4
toto5=$5
totoX=$@

# retrieve the username and hostname from the paramaters
while :
do
    case "$1" in
        -n) Username="$2"
            shift ; shift
            ;;
        -h) Hostname="$2"
            shift ; shift
            ;;
       -*)  shift
            ;;
        *) break
    esac
done

# if the samba user is anonymous then send mails to the postmaster
if [ "$Username" = "nobody" ];
   then
#    MailTo="admin"  # mgetty
    MailTo="faxmaster"  # hylafax
   else
    MailTo=${Username}
fi

if  [ "${MailTo}" = "" ] ; then
#    MailTo="admin"    # mgetty
    MailTo="faxmaster"  # hylafax
fi

zz1=`ps2ascii ${FAXFILE}`

#-----------------------------------
# Recherche des mots clés sur le fax
#-----------------------------------

# FAX : nom du document pour archive en pdf (facultatif)
# pour le document fax
FAXNAME=`ps2ascii ${FAXFILE} | awk '{ IGNORECASE=1 } /FAX-Name ?[ ] ?: ?[0-9a-zA-Z]+/ \
         {  $0=$0 "xxx"; \
	     zz0=$0; \
	     anfang=match($0,/FAX-Name ?[ ] ?: ?/); \
	     anfang=substr($0,anfang); \
	     gsub(/^FAX-Name[ ]*[:][ ]*/,"",anfang); \
	     gsub(/[ ]*---.*/,"",anfang); \
	     printf ("%s", anfang) \
        }' `

# FAX : nom du document  contenant les numéros de téléphone (obligatoire)
# pour le document fax
FAXNUM=`ps2ascii ${FAXFILE} | awk '{ IGNORECASE=1 } /FAX-Num ?[ ] ?: ?[0-9a-zA-Z]+/ \
         {  $0=$0 "xxx"; \
	     anfang=match($0,/FAX-Num ?[ ] ?: ?/); \
	     anfang=substr($0,anfang); \
	     gsub(/^FAX-Num[ ]*[:][ ]*/,"",anfang); \
	     gsub(/[ ]*---.*/,"",anfang); \
	     printf ("%s", anfang) \
	 }' `

# LISTE : nom du document  contenant les numéros de téléphone (obligatoire)
# pour les numéros de téléphone
LISTNUM=`ps2ascii ${FAXFILE} | awk '{ IGNORECASE=1 } /LIST-Num ?[ ] ?: ?[0-9a-zA-Z]+/ \
         {  $0=$0 "xxx"; \
	     anfang=match($0,/LIST-Num ?[ ] ?: ?/); \
	     anfang=substr($0,anfang); \
	     gsub(/^LIST-Num[ ]*[:][ ]*/,"",anfang); \
	     gsub(/[ ]*---.*/,"",anfang); 
	     printf ("%s", anfang) \
	 }' `
	 
#------------------------
# read file for multicast
#------------------------

FAXLIST=""
LISTPUBLI=""
NBRLIST=()	# num tél
NAMEDEST=()	# nom destinataire
NAMEEXP=()	# nom expéditeur
NAMEMAIL=()	# mail


if  [ "${FAXNUM}" != "" ] ; then
    FAXLIST="$FAXLIST1/$FAXNUM"
fi

if  [ "${LISTNUM}" != "" ] ; then
    LISTPUBLI="$FAXLIST1/$LISTNUM"
fi


charg_tab ()
{
    max=${#LISTSAUV[@]}
    i=0
    while [ $i -lt $max ]
    do
	# récup des données
	num_faxb=`echo ${LISTSAUV[i]} | cut -d"|" -f1`
	nom_destb=`echo ${LISTSAUV[i]} | cut -d"|" -f2`
	nom_expb=`echo ${LISTSAUV[i]} | cut -d"|" -f3`
	nom_mailb=`echo ${LISTSAUV[i]} | cut -d"|" -f4`
	# enlève blanc en début et fin de variable
	num_fax=$( echo $num_faxb )
	nom_dest=$( echo $nom_destb )
	nom_exp=$( echo $nom_expb )
	nom_mail=$( echo $nom_mailb )
	# remplissage tableau
	echo "------------------" >> $LOG
	echo "ave-b --$num_faxb-- sans-b --$num_fax--" >> $LOG
	echo "ave-b --$nom_destb-- sans-b --$nom_dest--" >> $LOG
	echo "ave-b --$nom_expb-- sans-b --$nom_exp--" >> $LOG
	echo "ave-b --$nom_mailb-- sans-b --$nom_mail--" >> $LOG
	echo "------------------" >> $LOG
	NBRLIST[i]=$num_fax
	NAMEDEST[i]=$nom_dest
	NAMEEXP[i]=$nom_exp
	NAMEMAIL[i]=$nom_mail
	let "i += 1"
    done
}

LISTSAUV=()

# chargement dans des tableau des infos pour faxer
if [ "${FAXLIST}" != "" ] && [ -s "${FAXLIST}"  ] ; then
    sv_ifs=$IFS
    IFS=$'\n'
    LISTSAUV=(`cat ${FAXLIST}`)
    IFS=$sv_ifs
    charg_tab
fi

# Récupération des infos pour faxer et sauvegarde dans un fichier
if [ "${LISTPUBLI}" != "" ] ; then
    ps2ascii ${FAXFILE} | sed  's/%%\[.*\]%%\(.*\)/\1/' |  sed '/^$/d' | tr -d '\f\n' | sed 's/LI.*---[ ]*\(.*\)/\1/' | sed 's/[|][\
]*[ ]*\([0-9][0-9]*[ ]*|\)/|\
\1/g' | sed 's/[|][\
]*[ ]*\([0-9][0-9]*[ ]*|\)/|\
\1/g'| sed '/^$/d' >  ${LISTPUBLI}
    
    sv_ifs=$IFS
    IFS=$'\n'
    LISTSAUV=(`cat ${LISTPUBLI}`)
    IFS=$sv_ifs
    charg_tab
fi


#---------------------------------------------------
# Envoi du fax aaprès vérification des infos fournis
#---------------------------------------------------

# if faxnumber is found fax the tempfile
# we do not check the validity of the faxnumber, let sendfax do this...

if  [ "${FAXLIST}" = "" ] &&  [ "${LISTPUBLI}" = "" ]; then
    (echo "To: ${MailTo}"
     echo "From: faxa "
     echo "Subject: your facsimile request failed"
     echo ""
     
     echo " The filename for fax numbers  is not recognized in your fax of"
     echo `date`
     echo ""
     echo "The name of this file is recognised via this text: "
     echo "   FAX-Num : xxxxxxxx --- for the document 'fax'"
     echo "            and "
     echo "   LIST-Num : xxxxxxxx --- for the document 'number list'"
     echo ""
     echo "No spaces are allowed between the characters"
     echo ""
     echo "--zz1--$zz1--"
     echo ""
    ) | 2>&1 $SENDMAIL -ffax -oi ${MailTo}

# no enreg in the file of fax number 
elif [  "${#NBRLIST[@]}" -le "0"  ] ; then
    (echo "To: ${MailTo}"
     echo "From: faxa "
     echo "Subject: your facsimile request failed"
     echo ""

     echo "The filename for fax numbers is empty of"
     echo `date`
     echo ""
     echo "The line of the document for fax number is recognised via this text: "
     echo "ddd-ddddddd| "
     echo ""
     echo " one number a line in the file "
     if [ "${FAXLIST}" != "" ]; then
	 echo " ${FAXLIST} : ${#NBRLIST[@]} records "
     else
	 echo " ${LISTPUBLI} : ${#NBRLIST[@]} records "
     fi
     echo ""
     echo "Please correct and retry"
     echo ""
     echo "--zz1--$zz1--"
     echo ""
    ) | 2>&1 $SENDMAIL -ffax -oi ${MailTo}
    
else
    
    #-----------------------------------------------------
    # envoi du document à faxer et d'un mail
    #-----------------------------------------------------
    
    if [ "${FAXLIST}" != "" ]; then
	
    	(echo "To: ${MailTo}"
    	echo "From: faxa "
    	echo "Subject: your facsimile request not failed"
    	echo ""

    	echo "The faxnumber is recognized in your fax of"
    	echo `date`
    	echo ""
    	echo "--${zz1}--"
    	echo ""
    	echo ""
    	echo "The faxnumber is recognised via this text:"
    	echo "   Fax-Nr-to : --${FAXNUMTO}--"
    	echo "   Fax-Nr-tos : --${FAXNUMTOS}--"
    	echo "   Fax-Nr-from : --${FAXNUMFROM}-- "
    	echo "   Fax-Name : --${FAXNAME}--"
    	echo "   fax-to : --${FAXTO}--"
    	echo "   fax-from : --${FAXFROM}--"
    	echo ""
    	echo "toto 1 : --$toto1--"
    	echo "toto 2 : --$toto2--"
    	echo "toto 3 : --$toto3--"
    	echo "toto 4 : --$toto4--"
    	echo "toto 5 : --$toto5--"
    	echo "toto X : --$totoX--"
    	echo ""
    	if [ "${FAXNUMTOS}" != "" ] ; then
		echo ""
		echo "Nombre de fax à envoyer : ${#NBRLIST[@]}"
		echo ""
    	fi

    	# transformation du postscript en pdf
    	ps2pdf13 -sPAPERSIZE=a4 "${FAXFILE}" "${FAXFILE}".pdf 2>> $LOG
    	# passage du fichier pdf au mail
    	uuencode ${FAXFILE}.pdf ${FAXFILE##/*/}.pdf 2>> $LOG

    	# copie du fichier postcript pour sauvegarde    
    	if [ "${FAXNAME}" != "" ] ; then
		cp "${FAXFILE}" "${FAXFILE_FIN}"/"${FAXNAME}".ps 2>> $LOG
		chmod a+r "${FAXFILE_FIN}"/"${FAXNAME}".* 2>> $LOG
    	fi

    	echo "-------Debut LOG -------"
    	echo ""
    	echo "`cat ${LOG}`"
    	echo ""
    	echo "------- fin LOG --------"
    
    	MailToz=""
    	FAXTOz=""
    	FAXFROMz=""
    
    	# Mail
    	if  [ "${MailTo}" != "" ] ; then
		MailToz="-f"
		MailTo=\"${MailTo}\"
    	fi
    
    	# Destinataire
    	if  [ "${FAXTO}" != "" ] ; then
		FAXTOz="-D"
		FAXTO=\"${FAXTO}\"
    	fi
    	# Expéditeur
    	if  [ "${FAXFROM}" != "" ] ; then
		FAXFROMz="-F"
		FAXFROM=\"${FAXFROM}\"
    	fi
    	# page de garde
    	Coverpagez="-C"
    	Coverpage="-"

    	echo " Liste des fax envoyés : "
    	echo "-------------------------"

    	# no multicasting
    	if  [ "${FAXNUMTO}" != "" ] ; then
		echo " Fax : ${FAXNUMTO} from ${FAXFROM} to ${FAXTO} mail ${MailTo}"
		echo ""
		
		# Hylafax
		eval sendfax -n  ${MailToz} ${MailTo} -d ${FAXNUMTO} ${FAXFILE}
		
		# Mgetty
		#echo "$faxspool ${MailToz}  ${MailTo} ${Coverpagez} ${Coverpage} ${FAXTOz} ${FAXTO} ${FAXFROMz} ${FAXFROM} ${FAXNUMTO} ${FAXFILE} "
		#eval $faxspool ${MailToz}  ${MailTo} ${Coverpagez} ${Coverpage} ${FAXTOz} ${FAXTO} ${FAXFROMz} ${FAXFROM} ${FAXNUMTO} ${FAXFILE} 2>${Err_Faxspool} 1>${Msg_Faxspool}
		# Log envoi Mgetty
		#if  [ -s "${Err_Faxspool}" ] ; then
	    	#	echo "---msg faxspool ---"
	    	#	echo "`cat ${Msg_Faxspool}`"
	    	#	echo "---err faxspool ---"
	    	#	echo "`cat ${Err_Faxspool}`"
	    	#	echo "---fin faxspool ---"
		#else
	    	#	Msg_1ligne=""
	    	#	read Msg_1ligne < ${Msg_Faxspool}
	    	#	echo "${Msg_1ligne}"
	    	#	NFax=`echo "${Msg_1ligne}" |    sed  's/.*\(F[0-9]*\).*/\1/'`
	    	#	echo " Numéro du fax enregistré : ${NFax}"
		#fi
	
    	# multicasting	
    	else
		j=0
		maxenreg=${#NBRLIST[@]}
		while [ $j -lt $maxenreg ]
    		do
	    		to_name=${FAXTO}
	    		from_name=${FAXFROM}
	    		to_mail=${MailTo}
			to_namez=$FAXTOz
			from_namez=${FAXFROMz}
			to_mailz=${MailToz}

			echo "name to : --${NAMEDEST[j]}--"
			echo "from name : --${NAMEEXP[j]}--"
			echo "mail : --${NAMEMAIL[j]}--"
			
	    		if [ "${NAMEEXP[j]}" != "" ] ; then
				from_name=\"${NAMEEXP[j]}\"
				from_namez="-F"
	    		fi
	    		if [ "${NAMEDEST[j]}" != "" ] ; then
				to_name=\"${NAMEDEST[j]}\"
				to_namez="-D"
	    		fi
	    		if [ "${NAMEMAIL[j]}" != "" ] ; then
				to_mail=\"${NAMEMAIL[j]}\"
				to_mailz="-f"
	    		fi
	    
	    		echo "  Fax $(($j+1)) : ${NBRLIST[j]} from ${from_name} to ${to_name} mail ${to_mail} "
	    		echo ""
			
			# Hylafax
			eval sendfax -n  ${to_mailz} ${to_mail} -d  ${NBRLIST[mj]} ${FAXFILE}
			
			# Mgetty
			#echo $faxspool ${to_mailz}  ${to_mail} ${Coverpagez} ${Coverpage} ${to_namez} ${to_name} ${from_namez} ${from_name} ${NBRLIST[j]} ${FAXFILE}
                        #eval $faxspool  ${to_mailz} ${to_mail}  ${Coverpagez} ${Coverpage} ${to_namez} ${to_name} ${from_namez} ${from_name} ${NBRLIST[j]} ${FAXFILE} 2>${Err_Faxspool} 1>${Msg_Faxspool}
			# Log envoi Mgetty
			#if  [ -s "${Err_Faxspool}" ] ; then
			#	echo "---msg faxspool ---"
			#	echo "`cat ${Msg_Faxspool}`"
			#	echo "---err faxspool ---"
			#	echo "`cat ${Err_Faxspool}`"
			#	echo "---fin faxspool ---"
	    		#else
			#	Msg_1ligne=""
			#	read Msg_1ligne < ${Msg_Faxspool}
			#	echo "${Msg_1ligne}"
			#	NFax=`echo "${Msg_1ligne}" | 	sed  's/.*\(F[0-9]*\).*/\1/'`
			#	echo " Numéro du fax enregistré : ${NFax}"
			#	#chmod a+r /var/spool/fax/outgoing/${NFax}/* 2> /tmp/Err_$$-chmod 
	    		#fi
	    		echo
	    		echo "-------------------------------------------------------------"
	    		let "j += 1"
		done
    	fi
    	) | 2>&1 $SENDMAIL -ffax -oi ${MailTo}


	#-------------------------------------------------------------------------
	# envoi d'un mail pour confirmation de l'enregistrement des numéros de fax
	#-------------------------------------------------------------------------

	else
	    sv_ifs=$IFS
	    IFS=$'\n'
	    LISTFAX=( `cat "${LISTPUBLI}"` )
	    IFS=$sv_ifs
	    max=${#LISTFAX[@]}
	    
	    # Le nombre d'enregistrement dans le fichier et dans le tableau correspondent
	    if [ ${#LISTFAX[@]} = ${#NBRLIST[@]} ]; then
		if  [  -s "${LISTPUBLI}"  ] ; then
		    (echo "To: ${MailTo}"
		    echo "From: faxa "
		    echo "Subject: your facsimile request not failed"
		    echo ""
		    
		    echo ""
		    echo "${FAXFILE}"
		    echo "--${zz1}--"
		    echo""
		    echo " Vous avez ${#NBRLIST[@]} numéros enregistrés dans ${LISTPUBLI}"
		    echo ""
		    echo "Liste des numéros enregistrés :"
		    echo ""
		    i=0
		    while [ $i -lt $max ]
		    do
			echo " Fax $(($i+1)) : ${NBRLIST[i]} -- Destinatire : ${NAMEDEST[i]} -- Expéditeur : ${NAMEEXP[i]} -- Mail : ${NAMEMAIL[i]}"
			let "i += 1"
		    done
		    ) | 2>&1 $SENDMAIL -ffax -oi ${MailTo}
		else
		    (echo "To: ${MailTo}"
		    echo "From: faxa "
		    echo "Subject: your facsimile request failed"
		    echo ""
		    
		    echo ""
		    echo "${FAXFILE}"
		    echo "--${zz1}--"
		    echo ""
		    echo " Vous avez $max enregistrements dans ${LISTPUBLI}"
		    echo ""
		    echo " Vous avez ${#NBRLIST[@]} numéros dans la liste des numéros"
		    echo " Chaque ligne doit commencer par des chiffres "
		    echo " suivis du caractère '|' "
		    echo ""
		    echo "Merci de vérifier votre liste et réessayer "
		    echo ""
		    ) | 2>&1 $SENDMAIL -ffax -oi ${MailTo}
		fi
	    else
		(echo "To: ${MailTo}"
		echo "From: faxa "
		echo "Subject: your facsimile request failed"
		echo ""

		echo ""
		echo "${FAXFILE}"
		echo "--${zz1}--"
		echo ""
		echo " Vous avez ${#NBRLIST[@]} numéros enregistrés dans le tableau"
		echo " Vous avez ${#LISTFAX[@]} numéros enregistrés dans ${LISTPUBLI}"
		echo ""
		echo "Liste des numéros enregistrés :"
		echo ""
		if [ ${#NBRLIST[@]} -lt ${#LISTFAX[@]} ]; then
		    maxenreg=${#LISTFAX[@]}
		else
		    maxenreg=${#NBRLIST[@]}
		fi
		i=0
		while [ $i -lt $maxenreg ]
		do
		    echo " Fax $(($i+1)) : ${NBRLIST[i]} -- ${LISTFAX[i]} "
		    let "i += 1"
		done
		) | 2>&1 $SENDMAIL -ffax -oi ${MailTo}
	    fi
	fi
fi

# remove the temp file
#rm -f ${FAXFILE}*
#rm -f ${Err_Faxspool}
#rm -f ${Msg_Faxspool}
#rm -f $LOG
#if  [ -e "${FAXLIST}" ] ; then
#    rm -f ${FAXLIST}
#fi
# end of script ######################################################