#!/bin/sh
# @(#)jobdonmsg.sh	1.1

LMPATHS="`/bin/dirname $0`/../lib/lmpaths"

if [ -f ${LMPATHS} ]
then
    . ${LMPATHS}
else
    . lmpaths
fi

# This is the script that gets run on the text LP is trying to send to the
# originator of a print job.
# If the message is a "job printed successfully" message, then send an
# abbreviated netevent message to the originator.
# If the message indicates that there was some sort of failure, send a
# netevent message stating that something went wrong, and the user should
# consult $PRINTLOG_PATH/queuename for the text of the message.
# Then, put that text in the appropriate printlog file. (Overwrite, don't
# append.)

#JOBDONDBG=yes
JOBDONDBG=
export JOBDONDBG

if [ "$JOBDONDBG" ]
then
    echo >/tmp/${JOBDONMSG_NAME}.out
    debugmsg () {
	    echo ${JOBDONMSG_NAME}: "$*" >>/tmp/${JOBDONMSG_NAME}.out
    }
else
    debugmsg () {
	:
    }
fi

LPOUT=`cat`
if [ "$LPOUT" = "" ]
then
	exit 0
fi

if [ $# != 5 -o ! -x "$NETEVENT_PATH" ]
then

	subj=`$LMECHO_PATH $LMECHO_PRJMAIL`
	$LMECHO_PATH $LMECHO_PRJNOMESSAGES | mailx -s "$subj" root
	exit 0
fi

LOGF=$PRINTLOG_PATH/$2
debugmsg LOGF = $LOGF

# $1 is the computername to which notification is to be sent
# $2 is the queuename to which the job was submitted
# $3 is the username of the originator of the job
# $4 is the size of the printjob
# $5 is the time it was submitted

NOTIFYNAME=$1
QNAME=$2
DNAME=$QNAME
USERNAME=$3
FILESIZE=$4
SUBMITTED=$5
JOBID=`echo $LPOUT | cut -d'-' -f2 | cut -d' ' -f1`
success=`echo "$LPOUT" | fgrep successfully`

debugmsg NOTIFYNAME=$NOTIFYNAME
debugmsg QNAME=$QNAME
debugmsg DNAME=$DNAME
debugmsg USERNAME=$USERNAME
debugmsg FILESIZE=$FILESIZE
debugmsg SUBMITTED=$SUBMITTED
debugmsg JOBID=$JOBID
debugmsg success=$success

if [ "$success" != "" ]
then
	#
	# NOTE: This is dependent on the format of the LP job completion
	# message.  If it ever changes, this has to change too.
	# Currently, the LP message contains a line as follows:
	#	has completed successfully on printer <printername>.
	# where <printername> is replaced with the name of the printer
	# that actually printed the job.
	#
	JOBSTAT=c
	DNAME=`echo "$success" | cut -d' ' -f6 | cut -d. -f1`
else
	JOBSTAT=e
	rm -f $LOGF
	(date ; echo "$LPOUT" ) | $UD_PATH -dz > $LOGF
	chmod +w $LOGF
fi

if [ "$JOBSTAT" = "c" ]
then
	$LMECHO_PATH $LMECHO_PRJCOMPLETE "$JOBID" "$DNAME"
else
	if [ -s $LOGF ]
	then
		$LMECHO_PATH $LMECHO_PRJERR1 "$JOBID" "$QNAME" "$PRINTLOG_PATH"
	else
		$LMECHO_PATH $LMECHO_PRJERR2 "$JOBID" "$QNAME"
	fi
fi | $NETEVENT_PATH -e printing -s SPOOLER -r $NOTIFYNAME -u $USERNAME -j $JOBID -a $JOBSTAT -m $SUBMITTED -z $FILESIZE -q $QNAME -d $DNAME > $DEV_NULL_PATH 2>&1
