#!/bin/sh
# faxg3make
# script by Xavier Roche
# usage: faxg3make <tempprefix>
# with existing <tempprefix>.FROM,<tempprefix>.TO,<tempprefix>.MESSAGE
# produces a <tempprefix>.g3 fax file
RANDSTR="$1"
NAME="$RANDSTR.TEMPLATE"
if test -n "$RANDSTR"; then
if test -f "$NAME"; then
if ! test -f "$RANDSTR.ps"; then
	# Make HTML template
	/bin/cat "$NAME" | /usr/bin/htmlreplace.pl "$RANDSTR" > "$RANDSTR.html"
	/bin/chmod 0744 "$RANDSTR.html"
	# Convert into ps
	/usr/bin/html2ps "$RANDSTR.html" > "$RANDSTR.ps"
	/bin/chmod 0744 "$RANDSTR.ps"
	>"$RANDSTR.2"
	/bin/chmod 0744 "$RANDSTR.2"
	# Find attachments is any
	ATTACH=`find ${RANDSTR%/*} -name "attach.*" -type f`
	# Convert ps + attach to standard ps
	/bin/mv "$RANDSTR.ps" "$RANDSTR.old.ps"
	/usr/bin/gs -sDEVICE=psmono "-sOutputFile=$RANDSTR.ps" -dNOPAUSE -q -dBATCH "$RANDSTR.old.ps" $ATTACH
	/bin/rm "$RANDSTR.old.ps"
	/bin/chmod 0744 "$RANDSTR.ps"
	# Make a pdf version, too
	/usr/bin/gs -sDEVICE=pdfwrite "-sOutputFile=$RANDSTR.pdf" -dNOPAUSE -q -dBATCH "$RANDSTR.ps"
	/bin/chmod 0744 "$RANDSTR.pdf"

	exit 0

	## ## ## ##
	/usr/bin/gs -sDEVICE=pbm "-sOutputFile=$RANDSTR.%d.pbm" -dNOPAUSE -q -dBATCH "$RANDSTR.ps"
	/bin/rm -f "$RANDSTR.ps"
	# List of pages (max 10 pages)
	GLIST=
	##for((i=0;$i<10;i++)) ; do
	for i in `echo 0 1 2 3 4 5 6 7 8 9`; do
		if test -f "$RANDSTR.$i.pbm"; then
			/usr/bin/pbm2g3 "$RANDSTR.$i.pbm" > "$RANDSTR.$i.g3"
			/bin/rm -f "$RANDSTR.$i.pbm"
			if test -f "$RANDSTR.$i.g3"; then
				GLIST="$GLIST $RANDSTR.$i.g3"
			fi
		fi
	done
	/usr/bin/g3cat -l $GLIST > $RANDSTR.g3
	/bin/rm -f $GLIST
	exit 0
fi
else
	echo "No such template ($NAME)"
fi
else
	echo "No parameter"
fi
/bin/rm -f "$RANDSTR.g3"
exit 1
