#!/bin/sh
#Tag 66272
# NOTE FOR DEVELOPERS:
#
# Please see the template_model.README file for more information
# about the structure and conventions in this file.  See also 'man sh'
#
# Also note that wherever you MUST change something for your printer,
# you should find an "XXX".  Search for them to see what you'll change.
#
# Change the first line of this file to '#!/bin/sh -x' for debugging output.
#
# bsdface - Interface for BSD network printing to PostScript printers
#
# NAME=BSD Remote Printer, DEVICE=BSD
#
# Required Configuration:
#
# Optional Configuration:
#
# logfile    may be set to the name of log file for error and status
#            messages.
#
# debug      may be set to non-zero to enable logging in $logfile.  The
#            flag may be turned on for individual requests by using the
#            -overbose option on the lp command line.
#
# Note: Do not change ANY characters up to the = in the next two assignments:
# various printer tools search for these EXACT characters.
#
NAME="BSD Remote Printer"
# XXX Change the TYPE= line to be the appropriate type.
TYPE=MonoPostScript

# HOSTNAME should be set to the name of the local host.
# HOSTPRINTER should be set to the name of the target printer on
# the BSD spooling system.
#
HOSTNAME=
HOSTPRINTER=

# First grab the command line arguments passed to the model file:
#
printer=`basename $0`				# the printer's name
jobid=$1					# job sequence id number
username=$2					# user name
title="$3"					# job title  
copies=$4					# number of copies
options="$5"					# -o options
shift 5						# discard args up to filenames
files="$*"					# input file(s)
firstfile=$1
lprnames=""					# saves the print job names
bannerfile=""
remtitle=

##################################################################
#
# This section includes our global variable definitions.
#
##################################################################

# Append the stderr output of the filters and drivers to error log file:
#
logfile=/var/spool/lp/log		# lp spooler error log file
exec 2>> $logfile

# The directories and files used by this interface file:
#
TMPDIR=/var/tmp				# Directory to store temporary files
export TMPDIR				# Export so all programs we call use it
HOME=/var/spool/lp                      # Home used by cms libraries
export HOME

printdir=/usr/lib/print			# Path to filter/driver directory
datadir=$printdir/data 			# Path to data directory

# Boolean flags:
#
debug=0				        # Print debug info to log file?
exitcode=0				# Report what error code on exit?
faceup=0				# Does printer stack faceup?
banner=1				# Print a banner page?		#XXX
bestfit=1				# Rotate image to best fit?
reversetext=0				# Reverse text document page order?
WaitInterval=10 			# wait period to check BSD queue

# General integer variables:
tagjobid=0	  			# Process ID of tagging process: 0=none

##################################################################
#
# Locations and options for filters and drivers:

# Non-printer-specific filters and drivers:
#
  # Text to PostScript Filter Options:
  #
  text2ps=$printdir/text2ps
  IMPR_TEXT2PSOPTS="-J $printer"
  export IMPR_TEXT2PSOPTS

  # SGI Image to PostScript Filter Options:
  #
  IMPR_SGI2PSOPTS="-C w -B"						#XXX
  export IMPR_SGI2PSOPTS

  # Other Image to STIFF Filter Options:
  #
  IMPR_IMG2STIFFOPTS=""
  export IMPR_IMG2STIFFOPTS

  # PostScript Page Order Manipulation Filter Options:
  #
  IMPR_PSFILTOPTS=""
  export IMPR_PSFILTOPTS

  # File Typer and File Type Converter:
  #
  filetyper=/usr/sbin/wstype	
  filetyperopts="-d /usr/lib/filetype/workspace.ctr"
  fileconvert=/usr/sbin/fileconvert
  fileconvertopts="-c /usr/lib/filetype/workspace.ctr"
  
# Printer-specific Filters:			
#
  # Device-Specific Printer Driver and options: 			#XXX
  # A simple driver to update the status database file.
  #
  driver=$printdir/lstatus						

##################################################################
#
# This section defines convenience functions for later use.
#
##################################################################

SetDebug()								#XXX 
#
# This routine turns on debug mode for all appropriate programs.
{
	# Non-printer-specific filters:
	#
	debug=1
	IMPR_SGI2PSOPTS="$IMPR_SGI2PSOPTS -D"
	IMPR_IMG2STIFFOPTS="$IMPR_IMG2STIFFOPTS -D"
	IMPR_TEXT2PSOPTS="$IMPR_TEXT2PSOPTS -Q"

	# Printer-specific filters:	
	#
}


ReportUnknownOption()
#
# Prints a useful error message when an unknown option is parsed.
# Expects the unknown option as argument 1 and the filename as arg 2. 
{
	echo $printer: $jobid $username : Unknown command line \\c >> $logfile
	echo option :: $1 :: while printing the following: \\c >> $logfile
	echo :: $2 :: - `date` >> $logfile
}


PrintMessage()
#
# Prints a text-only error message to the printer.
# Expects the strings to print as arguments, in order.
# Separates strings by spaces, so make sure to insert newlines appropriately.
{	

	 echo $* \
	      | $text2ps -J$printer \
	      | lpr -P$HOSTPRINTER -h >> $logfile

}


RemoveTempFiles()
#
# Removes temporary files created by filters, if any.
#
{
	if [ -f $lprnames ]; then
		/bin/rm -f $lprnames
	fi
}


GetBSDId()
#
# This routine grabs the third element from the lpq output.
# lpq outputs 'Rank Owner Job Files Size' string and this
# routine grabs Job feild. BSDJobId is used by lprm command
# if the user decides to cancel the job.
{
    BSDJobId=$3
}


BeginTagging()
#
# This routine sets up the printer icon tagging job.
{
	poddir=/var/spool/lp/pod		# Path to POD directory
	interfacedir=/var/spool/lp/interface	# Path to interface directory

	$printdir/tagit $interfacedir/$printer $poddir/$printer.status \
			$TYPE 10 1 2> /dev/null &
	tagjobid=$!
}


EndTagging()
#
# This routine tells the tagging job, if any, to stop tagging the printer.
{
	if [ $tagjobid -gt 0 ]; then
	   kill -TERM $tagjobid 	2> /dev/null
	fi
}	   


CleanUpAfterJob()
#
# Performs any required cleanup at the end of each job.
{
	if [ $debug != 0 ]; then 
		echo "Cleaning up after job." >> $logfile
	fi
	RemoveTempFiles
	EndTagging
}


SetCancelTrap()
#
# This routine sets up the proper trap command.
# When a job is cancelled, the spooler sends us a SIGTERM.
# We could also get a SIGHUP or a SIGINT, so we'll catch those.
#
# It removes any temporary/intermediate files created while filtering.
# It also calls EndTagging to stop the backgrounded tagging process.
{
	trap '
		# cancel the job from BSD queue
		lprm -P$HOSTPRINTER $BSDJobId  2>&1 >> /dev/null
		# Update the status file back to Idle state.
		$driver $printer idle >> /dev/null
		CleanUpAfterJob
		exit' 1 2 15  	# catch SIGHUP, SIGINT, and SIGTERM
}


ReportBadFile()
#
# Report unknown file type to printer log and spooler log.
# Expects as arguments the filename and filetype, in that order.
# Sets the global flag exitcode to indicate a bad file was sent.
{
	filetype="`$filetyper $filetyperopts $1 | /usr/bin/cut -d\  -f2-`"
	echo "$printer: File '$1' is of unprintable type '$filetype'.\n" \
	     >> $logfile
       	PrintMessage "Printer $printer could not print file '$1'\n" \
		     "Fileconvert could not convert this file of type" \
		     " '$filetype' to a printable format.\n"
	exitcode=8
}


TestExitStatus()
#
# Checks exit status from last executed command and reports
# an intelligent error message if and only if an error has occurred.
# Expects as argument 1 the exit code of the last command.
# Expects as argument 2 a string describing the last command.
# Expects as argument 3 the file or files being processed.
{
	# NOTE TO DEVELOPERS: 
	# The following list are error codes specific to the driver.
	# If the driver exits with an error code, we want to present
	# the user with a useful error message so they'll understand 
	# what really happened, not just get an 'error code X' message.
	#
	# NOTE: We include only one example error code for brevity.
	# REMEMBER: You must change these errorcodes for each driver!
	#
	err_emptyinput=12;  # Driver received empty or short input file
	
	case $1 in
	# 
	# Handle the common driver errors explicitly, so user gets
	# better idea what went wrong rather than just uninformative
	# message "an error occurred."  
	#
	0 ) # no error, do nothing
	;;

	$err_emptyinput ) 
	   # Driver reported empty input file. 
	   # The usual cause of this is that upstream filters died. 
	   echo $printer: Exit code $1 while $2. >> $logfile
	   PrintMessage "Printer $printer could not print file '$3':\n" \
			"The printer driver reported that an empty" \
			" or incomplete image was produced by fileconvert.\n\n" \
			"HINT: Was the PostScript code valid?" \
			"  Did it include a 'showpage' command?\n" \
			"Check the spooler log file $logfile for more details.\n" \
			"The PostScript interpreter may have reported" \
			" an error in the logfile."
	;;

	* ) # default case, print mostly useless error message.
	   echo $printer: Exit code $1 while $2. >> $logfile
	   PrintMessage "Could not print file '$3':\n" \
			"Exit code $1 while $2."
	;;
	esac
}


PrintBannerPage()
#
# Prints a banner page by appending the username, realusername, jobid,
# printername, timestamp, and BannerPage routine invocation
# onto a pre-defined PostScript banner program and then
# printing the resulting PostScript program.
# 
{
# Location for banner page program
#
bannerprogram=$datadir/BannerPage

# temporary banner file
#
bannerfile="$printer.banner.$jobid"
bannerfile="`echo $bannerfile | /usr/bin/cut -c-33`"

if [ ! -f $bannerprogram ]; then
        echo "$printer: ERROR: Unable to find $bannerprogram file." >> $logfile
        echo "$printer: Banner Page can not be printed." >> $logfile
	PrintMessage "ERROR:" \
		"Unable to find banner page program '$bannerprogram'.\n"\
		"A banner page can not be printed."
        return
fi

# Get the user's real name if we can.
#
realname=`finger -bfmp $username|nawk '{print substr($3, 2); exit}' FS=':'`

# Send the prolog file and the job specific info to the PS renderer:
#
echo "($realname) ($username) ($jobid) ($printer) (`date`) ($title) BannerPage" \
     | cat $bannerprogram - \
	 > $bannerfile

# Report intelligent error if we failed 
#
TestExitStatus $? "printing banner page" "Impressario Banner Page"
}


ParseOptions()
#
# Parses -o command line options and sets appropriate global variables.
{

# Loop through the options, shifting off those read at end of loop.
#
count=$#
while [ "$count" -gt 0 ]
do
	case $1 in
	#
	# General model file options
	#
		# Print a banner page?
		#
		-banner | banner)	argcnt=1; banner=1	;;
		-nobanner | nobanner | -h | h)	
					argcnt=1; banner=0	;;

		# Print debug (verbose) messages into spooler log file?
		# 
		-debug | debug)	        argcnt=1; SetDebug	;;	
		-verbose | verbose)    	argcnt=1; SetDebug	;;
		-noverbose | noverbose) argcnt=1;         	;;

	#
	# Non-printer-specific filtering options
	#
	# General filtering options:
	#

	#
	# Printer-specific filtering options:  
	#

	# PostScript page order filter options
	#
		# Print the specified page range, two integer page numbers
                -pspagerange | pspagerange) argcnt=3;
                        IMPR_PSFILTOPTS="$IMPR_PSFILTOPTS -p$2-$3" ;;

       		# Reverse the PostScript page order
                -psreversepage | psreversepage) argcnt=1;
			 IMPR_PSFILTOPTS="$IMPR_PSFILTOPTS -r" ;;

                # Select odd pages only
                -psoddpage | psoddpage) argcnt=1; 
			IMPR_PSFILTOPTS="$IMPR_PSFILTOPTS -o" ;;

                # Select even pages only
                -psevenpage | psevenpage) argcnt=1; 
			IMPR_PSFILTOPTS="$IMPR_PSFILTOPTS -e" ;;

	# Image filter options:
	#
		
		# Rotate the image in integer degrees
		-rotate | rotate)      	argcnt=2; 	
			IMPR_SGI2PSOPTS="$IMPR_SGI2PSOPTS -r $2";
			bestfit=0			     	;;
		# Rotate the final image to the best fit orientation
		-bestfit | bestfit)	argcnt=1;  bestfit=1 	;;
		# Flip the image, producing a mirror image.
		-flip   | flip)		argcnt=1; 
			IMPR_SGI2PSOPTS="$IMPR_SGI2PSOPTS -f"	;;
		# Scale the image to fit the page.
		# Takes a float argument, see appropriate man pages.
		-zoom   | zoom)		argcnt=2; 
			IMPR_SGI2PSOPTS="$IMPR_SGI2PSOPTS -z $2";;
		# Scale the final image size to match the
		#  specified input resolution, in pixels per inch.
		-ppi    | ppi)  	argcnt=2; 
			IMPR_SGI2PSOPTS="$IMPR_SGI2PSOPTS -p $2";;
		# Set the amount of gamma warping for the image
		-gamma  | gamma) 	argcnt=2;
			IMPR_SGI2PSOPTS="$IMPR_SGI2PSOPTS -G $2";;
					
	# Text filter options	
	#
	# If you get any of these switches, 
	# you should use the PostScript filter on the text, 
	# not the fast path filter (if your printer supports one.)

		# Use PostScript for text processing.
		-pstext | pstext)  	argcnt=1; ;;

		# Page orientation
		-landscape | landscape) argcnt=1;
			IMPR_TEXT2PSOPTS="$IMPR_TEXT2PSOPTS -H"  ;;
		-portrait  | portrait)  argcnt=1;
			IMPR_TEXT2PSOPTS="$IMPR_TEXT2PSOPTS -V"  ;;

                # Font name, argument is font name as specified in man page
                # for the filter associated with text to PostScript conversion.
		# Typically this filter is text2ps(1).
		-fontname  | fontname)  argcnt=2;
			IMPR_TEXT2PSOPTS="$IMPR_TEXT2PSOPTS -F$2";;

		# Font size, in points, a positive integer.
		-fontsize  | fontsize)  argcnt=2;
			IMPR_TEXT2PSOPTS="$IMPR_TEXT2PSOPTS -P$2bp"       ;;

		# Margin sizes: top, bottom, left and right margins specified
		# as <float_value> [in | cm | mm]
		-topmargin | topmargin) argcnt=3;
			IMPR_TEXT2PSOPTS="$IMPR_TEXT2PSOPTS -T$2$3"       ;;
		-bottommargin | bottommargin) argcnt=3;
			IMPR_TEXT2PSOPTS="$IMPR_TEXT2PSOPTS -B$2$3"    ;;
		-leftmargin | leftmargin) argcnt=3;
			IMPR_TEXT2PSOPTS="$IMPR_TEXT2PSOPTS -L$2$3"      ;;
		-rightmargin | rightmargin) argcnt=3;
			IMPR_TEXT2PSOPTS="$IMPR_TEXT2PSOPTS -R$2$3"     ;;
		
		# Number of columns on page, a non-negative integer
		-columns   | columns) 	argcnt=2;
			IMPR_TEXT2PSOPTS="$IMPR_TEXT2PSOPTS -M$2";;
		
		# Number each page : [tb][lcr] [number]
		-numberpages | numberpages)  argcnt=3;
			IMPR_TEXT2PSOPTS="$IMPR_TEXT2PSOPTS -N$2$3";;

		# Reverse the page order?
		-reversepages | reversepages)     argcnt=1; reversetext=1 ;;
		-noreversepages | noreversepages) argcnt=1; reversetext=0 ;;

		# Gaudy page header
		-gaudy | gaudy)     argcnt=1; gaudymode=1   ;;
		-nogaudy | nogaudy) argcnt=1; gaudymode=0   ;;

                # Preformatted manual page printing
                -manpage | manpage)     argcnt=1;
			IMPR_TEXT2PSOPTS="$IMPR_TEXT2PSOPTS -F Courier10 \
					-S plain -M 1 -K 66 -m fit" ;;

			
	#
	# All other options are discarded with an appropriate message
	#
		*)  argcnt=1;  ReportUnknownOption $1 $files        ;;
	esac
	shift $argcnt
	count=`expr $count - $argcnt`
done

# Now do post-processing on the parsed arguments. 

# Set the gaudy mode for the text filter:
#
if [ "$gaudymode" = 1 ]; then
   IMPR_TEXT2PSOPTS="$IMPR_TEXT2PSOPTS -G -O 0.4pt" ;
fi

# Turn off page reversal for printers that print facedown. 
#
if [ $faceup = 0 -a $reversetext = 0 ]; then 
   	 IMPR_TEXT2PSOPTS="$IMPR_TEXT2PSOPTS -U";
elif [ $faceup != 0 -a $reversetext != 0 ]; then
   	 IMPR_TEXT2PSOPTS="$IMPR_TEXT2PSOPTS -U";
fi     

# Check whether BestFit be turned on in sgi2ps (see sgi2ps man page)
#
if [ $bestfit != 0 ]; then 
   	 IMPR_SGI2PSOPTS="$IMPR_SGI2PSOPTS -F";
fi     

}


##################################################################
#
# This section is the actual body of the interface program.
#
##################################################################

# First verify that our prerequisites are in place.  
#
# In our case, the minimum check includes checking that:
# the log file is writable, the printer type is set and
# the driver and filter ctr file exist.
#
# Ideally, if an error were detected, we would respool the job
# after disabling the printer but before exiting.  
# This would preserve the print job instead of dropping it on the floor.

# Set LOGNAME to ensure we can disable a printer queue:
LOGNAME=lp
export LOGNAME

if [ ! -w "$logfile" ]; then
        disable -r"Can't write to spooler log.  Please check permissions." \
		$printer  2>&1
        exit 2
fi

if [ "$TYPE" = "" ]; then 
	disable -r"Printer type not defined.  Please reinstall printer." \
		$printer  1>>$logfile 2>&1
	exit 2
fi

if [ ! -x "$driver" ]; then
	disable -r"$driver is not an executable.  Please reinstall $driver." \
		$printer 1>>$logfile 2>&1
	exit 2
fi
   
# Future releases of Irix will not have .ctr files (routeprint will
# map .ctr to .otr for printing at that time).  We will no longer 
# check for the workspace.ctr file
#
#if [ ! -r /usr/lib/filetype/workspace.ctr ]; then
#	disable -r"WorkSpace filetype database not built.  Please type 'su ; cd /usr/lib/filetype ; make'" \
#		$printer 1>>$logfile 2>&1
#	exit 2
#fi

#
# Make sure remote host and printer names are configured.
#
if [ -z "$HOSTNAME" ]; then
	disable -r"$PRINTER: Local host name not configured. Reinstall printer" \
			$printer 1>> $logfile 2>&1
	exit 1
fi
if  [ -z "$HOSTPRINTER" ]; then
	disable -r"$PRINTER: BSD printer name not configured. Reinstall printer" \
			$printer 1>> $logfile 2>&1
	exit 1
fi

remtitle="${username}@$HOSTNAME:"

if [ -z "$title" ]  # do lpr -J "$title"
then
	remtitle="$remtitle `basename $firstfile`"
else
	remtitle="$remtitle $title"
fi
##################################################################

# Set up the signal handler to handle jobs cancellation
# 
SetCancelTrap

# Now parse the options passed using the -o switch:
#
ParseOptions $options

# Report that the job has begun:
#
if [ $debug != 0 ]; then
        echo $printer: $jobid $username "$title" Start - `date` >> $logfile
        echo $printer: "options: $options" >> $logfile
fi

# Update the status database before job filtering starts.
#  This is required because printer config may have changed between
#  jobs, and because the driver will update the status file that
#  the filters read.  
#  This is used for forcibly updating dynamic printer options like resolution.
#
$driver $printer busy >> /dev/null

# Fire off the sub-process which will tag this model file
#  with the appropriate print engine type and status for active icons:
#
BeginTagging


##################################################################
#
# Now do the real printing:
#  (1)  Print a banner page if requested.
#  (2)  Typecheck and filter each file in $files one by one.

	if [ $banner != 0 ]; then
		PrintBannerPage
	fi

for file in $files
do
	# Create a temp file filename, to be used by filters or driver.
	# After each file is processed, the RemoveTempFiles routine removes
	# all the temp files.
	#
	# unqid is a stripped jobid. lpq can not handle long names.
	# Goal is to cut down the fix number of chars in tmpfile variable.
	#
	unqid="`echo $jobid | cut -c1,2`"
	unqid="$unqid`echo $jobid | cut -d- -f2`"
	tfile="$TMPDIR/$unqid.`basename $file`"
	tmpfile="`echo $tfile | /usr/bin/cut -c-33`"

	# Keep track of the first file since lpq abbreviates with three dots
	# if the Files feild is more than 33 chars.
	#
	if [ -z "$lprnames" ]; then
		firstfile=$tmpfile
	fi

	# Use fileconvert to convert to the printer's native format.
	# For raster printers, it is ImpressarioRasterBitmap.
	# For PostScript printers, it is ImpressarioPostScriptFile.
	#
	CMD=`$fileconvert $fileconvertopts -d ImpressarioPostScriptFile \
		$file 2> /dev/null` #XXX

	if [ $? = 0 ]; then
	   # OK, conversion successful, execute the returned sh cmd file
	   # and send the results to the printer.
	   sh -c "$CMD" > $tmpfile

	   # Report intelligent error if we failed 
	   #
	   TestExitStatus $? "Processing $file via $fileconvert" $file

	else
	   # Couldn't convert it to printable format, so give up.
	   #	
	   ReportBadFile $file
	fi
	# If there is more than one file then make a list of them.
	# All the files will be sent to lpr as a single job.
	#
	lprnames="$lprnames $tmpfile"
done

	# Ok, now it is filtered into PostScript, lpr the files.
	#
	# Print the banner page first if the printer prints face down:
	#
	if [ ! -z "$bannerfile" ]; then
		if [ $faceup = 0 ]; then
			lprnames="$bannerfile $lprnames"
			firstfile=$bannerfile
		else
			lprnames="$lprnames $bannerfile"
		fi
	fi
	lpr -P$HOSTPRINTER -#$copies -J"$remtitle" -h $lprnames >> $logfile

	# Get the BSD queue, and parse the BSD Job Id.
	# Later JobId will be useful if the user decides to cancel the
	# job.
	#
	BSDqueue=`lpq  -P$HOSTPRINTER | grep $firstfile`
	GetBSDId $BSDqueue
	while [ -n "`lpq -P$HOSTPRINTER | grep $firstfile 2>/dev/null`" ]
	do
		# do it all again in $WaitInterval seconds
		sleep $WaitInterval
	done
	# Update the status file back to Idle state.
	$driver $printer idle >> /dev/null

##################################################################
#
# Done filtering all files.  Clean up and exit.

# Perform any cleanups that had to wait until the job ended.
#
CleanUpAfterJob

# Report end of job.
# 
if [ $debug != 0 ]; then
	echo $printer: $jobid End - `date` >> $logfile
fi

# Now check whether we had unsupported file types in the file list
# If so, exit with that code.
#
exit $exitcode
