#!/bin/sh 
#
# colorps_model - lp interface for generic Color PostScript printer.  
#  Supports connection via built-in paralleil port or over the net to
#  a network card (i.e. HP JetDirect card).  Sends Color PostScript to
#  the pritner (can also be switched to monochrome).  
#
# $Revision: 1.6 $
# $Date: 1996/04/21 22:22:35 $
#
# Info for administration tools (these are parsed by various tools, 
# do not change these):
#
# NAME=Generic Color PostScript (Face Down Pages), DEVICE=CENTRONICS, OPTIONS=FACEUP=0
# NAME=Generic Color PostScript (Face Up Pages), DEVICE=CENTRONICS, OPTIONS=FACEUP=1
# NAME=Generic Color PostScript (Face Down Pages), DEVICE=NETPRINTER, OPTIONS=FACEUP=0 NETWORK=1 OUTSOCK=9100
# NAME=Generic Color PostScript (Face Up Pages), DEVICE=NETPRINTER, OPTIONS=FACEUP=1 NETWORK=1  OUTSOCK=9100
#
NAME=
TYPE=ColorPostScript
GUI_CLASS=GenericPostScript
#
# 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)

##################################################################
#
# 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

#  Does the printer print text facing up?

FACEUP=0				

# If printing to a printer directly connected to the network then
# NETWORK should be set to 1 and NETPRINTER is the name or IP address
# of the network printer (name typically found in /etc/hosts).

NETWORK=0                               
NETPRINTER=

# Network port to write to.  9100 is HP Jetdirect card and EX. 
# The JetDirect 3Plus EX uses 9100, 9101, and 9102 for ports 1, 2, and 3.
# Many other vendors use same port as HP.  OUTSOCK is port to write to.
# INSOCK is socket to read for status (for future use -- status
# now read from same socket address as specified a by OUTSOCK).

OUTSOCK=9100
INSOCK=9100

# Boolean flags:
#
debug=0				        # Print debug info to log file?
exitcode=0				# What error code should we report
banner=1				# Print a banner page?
bestfit=1				# Rotate image to best fit?
reversetext=0				# Reverse text document page order?

# 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 cmyk"
  export IMPR_SGI2PSOPTS

  # 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"
  
  # Driver and options, will be set to plpdriver or netdriver below:   
  #
  driver=""
  driveropts=""

  # Driver to drive the parallel port:
  #
  plpdriver=$printdir/phandler
  plpdriveropts="-P $printer"

  # Driver to drive a printer directly connected to the network
  #
  netdriver=$printdir/nethandler
  netdriveropts=" -x $NETPRINTER -j$jobid+$username -p $OUTSOCK -P $printer
"

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

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

	# Printer-specific filters:	
	#
        plpdriveropts="$plpdriveropts -D"
        netdriveropts="$netdriveropts -l $logfile -s $logfile"
}

SetDeviceDriver()
#
# Set the driver for the output device to drive a parallel port or
# a network device
{
        if [ $NETWORK != 0 ]; then
           driver="$netdriver"
           driveropts="$netdriveropts"
        else
           driver="$plpdriver"
           driveropts="$plpdriveropts"
        fi
}


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 \
             | $driver $driveropts 1>>/dev/null 2>&1
}


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
	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 '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.
{
	# The following list contains 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.
	#
	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

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 - | $driver $driveropts 1>>/dev/null 2>&1

# 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:  
	#
                # Whether to print using color or monochrome:
                -color | color)   argcnt=2;
                	IMPR_SGI2PSOPTS="$IMPR_SGI2PSOPTS -C $2";;

                # What papersize to request?  Only the plp driver can
                # accept this (and it will be called to update the POD
                # status with the paper size).  This driver does not send
                # the paper size to the pritner; but, it needs to know the
                # size to pages have the correct number of lines, etc.

                -papersize | papersize) argcnt=2;
                        plpdriveropts="$plpdriveropts -S $2";
                        IMPR_TEXT2PSOPTS="$IMPR_TEXT2PSOPTS -s $2";; 

	# 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	
	#
		# 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 $text2ps.
		-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.
#
##################################################################

# Set the device driver string before checking it, below.
#
SetDeviceDriver

# 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 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

##################################################################

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

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

# Re-set the device driver after options parsed.
#
SetDeviceDriver

# Report that the job has begun:
#
if [ $debug != 0 ]; then
        echo $printer: $jobid $username "$title" Start - `date` >> $logfile
        echo $printer: "options: $options" >> $logfile
        exec 2>> $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.  $plpdriveropts will have the paper size
#  This is used for forcibly updating dynamic printer options like papersize.
#  We use the plpdriver because it can do this for us.
#
$plpdriver -s -e -u $plpdriveropts

# 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.

# Print the banner page first if the printer prints face down:
#
if [ $banner != 0 -a $FACEUP = 0 ]; then
   PrintBannerPage
fi

for file in $files
do
        # Try converting it to printer driver format data using fileconvert.

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

	if [ $? = 0 ]; then
	   # OK, conversion successful, execute the returned sh cmd file
	   # and send the results to the printer.
	   copy=1
	   while [ $copy -le $copies ]
	   do

                if [ $debug != 0 ]; then
                   # Log the commands that actually get run.
                   echo "$printer: CMD:$CMD | $driver $driveropts" >> $logfile             
                   echo "$printer: IMPR_SGI2PSOPTS:$IMPR_SGI2PSOPTS" >> $logfile
                   echo "$printer: IMPR_TEXT2PSOPTS: $IMPR_TEXT2PSOPTS"  >> $logfile
                   exec 2>> $logfile
                fi
           
                sh -c "$CMD" | $driver $driveropts 1>>/dev/null 2>&1

	   	# Report intelligent error if we failed 
	   	#
	   	TestExitStatus $? "Processing $file via $fileconvert" $file
	   	copy=`expr $copy + 1`
	   done
	else
	   # Couldn't convert it to printable format, so give up.
	   #	
	   ReportBadFile $file
	fi
done

# Print the banner page last if the printer prints face up:
#
if [ $banner != 0 -a $FACEUP != 0 ]; then
   PrintBannerPage
fi

##################################################################
#
# 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
