#!/bin/sh
# lpstat,hpstat: report lp/hp status as cmdline or filenames AND return value
#----------------------------------------------------------------------------
: ${LPTOOLS=/usr/local/lib}
case $0 in
  *hpstat) DAEMON=hpd ;;
  *)       DAEMON=lpd ;;
esac

LPJOB=lpjob
case $1 in
  -c*) LPJOB=lpcmd		  # report commandline
       HDR=Commandline ;;
  -v*) HDR='File(s)' ;;		  # report print jobs
  -d*) cd /usr/spool/$DAEMON      # report unreferenced spool files
       stray=
       for file in `/bin/ls | grep -v 'cf[0-9]*'` ; do
         grep -s U$file cf[0-9]* || echo $file && stray="$stray $file"
       done 
       test -z "$stray"
       exit $? ;;		  # .. and quit
  -*)  echo "usage: $0 [-c|-v|-d]" ;;
esac

# Locate spool directory, and make list of controlfiles
#----------------------------------------------------------------------------
cd /usr/spool/$DAEMON
CTRLFILES=`/bin/ls cf* 2>/dev/null`
if [ -z "$CTRLFILES" ] ; then 
  test -n "$HDR" && echo "No requests to process"
  HDR=
fi

# Handle verbose options and quit
#----------------------------------------------------------------------------
if [ "$HDR" != "" ] ; then
  echo "			Printer-Queue"
  echo
  echo "  ID\tDate\t      User\t$HDR"
  echo
  ${LPTOOLS}/$LPJOB $CTRLFILES
  echo
  exit $?
fi

DPID=`$LPTOOLS/lpid`		# Check if there is a lock file
LOCK=$? 
if [ -n "$CTRLFILES$DPID" ] ; then
  set `/bin/ps -an`		# Check if daemon is running
  while [ $# -gt 1 ] ; do
    test "$2" = "/usr/lib/$DAEMON" && PSID=$1 && break
    shift
  done
  test -n "$PSID" && exit 0	# daemon running...
  LPSTAT="Daemon stopped; "
else
  LPSTAT=`/usr/lib/$DAEMON 2>&1`    # Check if printer is powered on.
fi
test $LOCK -ne 1 && LPSTAT="${LPSTAT}Queue blocked"

test -z "$LPSTAT" && exit 0
echo "\n$LPSTAT\n"
exit 1
