#!/bin/sh
#
# REQUIRES: three arguments:
#           target:	    the name of the printer to be tagged.
#			    must be a taggable printer interface script.
#	    statusfile:	    the full path to the status file to watch.
#			    status file should obey printer status DB spec.
#	    printertype:    a token describing the printer type.
#			    should be one of the defined types only.
#			    (See case printertype below.)
# OPTIONAL: one or two additional arguments:
#		updateInterval: number of seconds between tagging runs	
#		numberOfUpdates: number of tagging runs after tagit is killed.
#
# MODIFIES: targetfile, logfile
#
# EFFECTS:
# This is a program which parses the printer.status file, 
# watches the status line, and whenever it changes, tags targetfile 
# with the appropriate tags, which depend on printer type and status.
#
# This program EXPECTS to be killed, so the trap is ultra-important.
# We don't exit on our own unless we can't do our job.
#
# COMMENTS:
#
# Printer type is a system-wide defined token, e.g., ColorPostScript.
# Valid printer tags range from 0x10200-0x102FF.
# This program encapsulates the active tagging of those tag numbers.  
# Only this program and the ftr rules care what the tag #s are.
#
# FUTURE PLANS:
#
# In an ideal world, this script would be replaced with a program
# which used FAM, had low overhead, etc..  This isn't an ideal world.  Yet.
#
#
# AND NOW, FOR SOMETHING COMPLETELY DIFFERENT:  (the program!)

# Append all stderr output to the spooler log file
LOGFILE=/var/spool/lp/log
exec 2>> $LOGFILE

# Whether verbose messages get logged to logfile, true if VERBOSE > 0.
VERBOSE=0
 
# Some defines:
#
UpdateInterval=10 	# default time between polling updates, in seconds.
NumberOfUpdates=3	# default number of updates to perform after killed.
INVALIDTAG=-1
oldtag=$INVALIDTAG	# initial value for tagging variables, 
			#  set to invalidtag so we'll update at beginning
tag=0			# set these different for initial forced tagging

# Where printers live:
#
PRINTERPATH=/var/spool/lp/interface

# Tagging program:
#
TAGPROGRAM=/usr/lib/print/tagprinter

myname=`basename $0`
#
# Check number of command line arguments
#
if [ $# -lt 3 ]   # if not proper number of arguments,
then			# exit with an error
   echo "$myname: ERROR: not enough arguments passed in." >> $LOGFILE
   echo "$myname: Usage: $myname FileToTag FileToWatch TypeOfPrinter" >> $LOGFILE
   echo "$myname: 	 Optional arguments: UpdateInterval NumberOfUpdatesAfterKill" >> $LOGFILE
   exit 1
fi

#
# Grab command line arguments
#
target=$1	 	# the file to tag
statusfile=$2		# the status file to watch
printertype=$3		# the type of printer we're watching, for tag purposes.
if [ $# -ge 4 ]	# user specified an update interval
then	
	UpdateInterval=$4
fi
if [ $# -ge 5 ]	# user specified a number of times to update after kill 
then	
	NumberOfUpdates=$5
fi

# Set the printer name given the full pathname to the printer:
#
printername=`basename $target`


# Check existence of target file and grab its tag, if any.
#
if [ ! -s $PRINTERPATH/$printername ]	 # if file doesn't exist
then
    echo "$myname: ERROR: Target printer $printername does not exist!" >> $LOGFILE
    exit 1
fi



# Check existence of source file.
#
if [ ! -s $statusfile ]     # if file is of zero length, it doesn't exist
then
    echo "$myname: ERROR: Status file $statusfile does not exist!" >> $LOGFILE
    exit 1
fi


# Set some defines to make tagging easier.
#
# The base (type of printer) tags
#
Dumb=66048		   # 0x10200
DumbColor=66080		   # 0x10220
Raster=66112		   # 0x10240
ColorRaster=66144	   # 0x10260
Plotter=66176		   # 0x10280
PostScript=66208	   # 0x102A0
ColorPostScript=66240	   # 0x102C0
MonoPostScript=66272	   # 0x102E0

# Range check variables, so we don't try to tag an invalid number:
#
MINTAGNUM=66048		   # Idle Dumb printer
MAXTAGNUM=66288            # Unknown Network Watched MonoPostScript printer

# And now the state modifiers for those type tags:
#
Idle=0			   # 0x0
Busy=1			   # 0x1
Faulted=2		   # 0x2
Unknown=3		   # 0x3
IdleWatched=4		   # 0x4
BusyWatched=5		   # 0x5
FaultedWatched=6	   # 0x6
UnknownWatched=7	   # 0x7

NetIdle=8		   # 0x8
NetBusy=9		   # 0x9
NetFaulted=10		   # 0xA
NetUnknown=11		   # 0xB
NetIdleWatched=12	   # 0xC
NetBusyWatched=13	   # 0xD
NetFaultedWatched=14	   # 0xE
NetUnknownWatched=15	   # 0xF

# Set tag template based on printer type:
# Parse printer type and set the basetag.

case $printertype in
     Dumb|DUMB|dumb)
	  	  type=$Dumb 		;;
     DumbColor|DUMBCOLOR|dumbcolor)
		  type=$Dumb 		;;
     Raster|RASTER|raster)
		  type=$Raster 		;;
     ColorRaster|COLORRASTER|colorraster)
		  type=$ColorRaster 	;;
     Plotter|PLOTTER|plotter)
		  type=$Plotter 	;;
     PostScript|POSTSCRIPT|postscript)
		  type=$PostScript 	;;
     ColorPostScript|COLORPOSTSCRIPT|colorpostscript)
		  type=$ColorPostScript ;;
     MonoPostScript|MONOPOSTSCRIPT|monopostscript)
		  type=$MonoPostScript 	;; 	
     *)	  echo "$myname: ERROR: Unknown type $printertype" >> $LOGFILE
	  exit 1
	  ;;
esac		  

if [ $VERBOSE != 0 ]
then
	echo "$myname: Target printer is of type $type" >> $LOGFILE
fi

#
# And now the function to do the tagging stuff.
# We define a function so nawk will coexist with trap's syntax (the quote char)
#
perform_tagging()
{
  STATUS=`/usr/bin/awk '/[ \t]*[Oo][Pp][Ee][Rr][a-zA-Z]*[\t ]+[Ss][Tt][Aa][Tt][a-zA-Z]*/ {print}' $statusfile | /usr/bin/awk '{print $4}'`
 
  if [ $VERBOSE != 0 ]
  then
    echo "Printer $printername (type #'$type') status is $STATUS." >> $LOGFILE
  fi
	
  case $STATUS in
    idle|Idle|IDLE)      	 statustag=$Idle       ;;
    busy|Busy|BUSY)		 statustag=$Busy	;;
    faulted|Faulted|FAULTED)	 statustag=$Faulted	;;
    unknown|Unknown|UNKNOWN|unavailable|Unavailable|UNAVAILABLE)
    				 statustag=$Unknown	;;
    *)		    echo "$myname: Invalid status read: $STATUS" >> $LOGFILE
		    return 2
 		    ;;
  esac

  #
  # Now do the actual tagging: 
  # Add the type and state modifiers to get the final tag.

  oldtag=$tag			    # save last tag for comparison
  tag=`expr $type + $statustag`
  if [ $tag != "$oldtag" ]          # only update file if tag changed
  then          
      if [ \( $tag -lt $MINTAGNUM \) -o \( $tag -gt $MAXTAGNUM \) ];
      then
	 echo "tagit: WARNING: Bad tag #$tag attempted on printer '$printername': ignoring it.\n" >> $LOGFILE
      else	
         $TAGPROGRAM $printername $tag
      fi
  fi
}

# Set a trap to catch when we are killed.
# We expect to be killed, not to exit on our own!
# This ensures that we update status tags NumberOfUpdates more time(s)
# when the job ends or is cancelled and our parent process kills us.

trap '			

  while [ $NumberOfUpdates -gt 0 ]
  do
        sleep $UpdateInterval
	perform_tagging
	NumberOfUpdates=`expr $NumberOfUpdates - 1`
	if [ $VERBOSE != 0 ]
	then
		echo "$myname: Number of updates left before exiting: $NumberOfUpdates" >> $LOGFILE
	fi
  done	

exit' 1 2 15  


#
# OK, here's our main loop:
#

while [ ! -n "" ] # repeat forever, waiting to be killed and trap
do  
  # loop forever until killed, polling statusfile every $UpdateInterval secs,
  # and updating the printer interface file with the new tag retrieved from it.

  perform_tagging
 
  sleep $UpdateInterval

done	# end of infinite while loop

