#!/bin/sh
#
# This is a temporary replacement for buggy lprm from spooling system CUPS.
# Fixed bug is: original can't really stop active job
# Autor: Yura Kalinichenko <yuk@iceb.vinnitsa.com>
#
# Additional requirements:
# 	all users must have permission for `kill' as user `lp'.
# 	For example, you can enter in file `sudoers' next string:
# 	ALL     ALL=(lp) NOPASSWD: /bin/kill
#
# Yes, now every user can kill any printing, but...
#

CMDLINE=`getopt -o P: -- "$@"`
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 255 ; fi
eval set -- "$CMDLINE"

while true ; do
	case "$1" in
	-P) PRINTER=$2
            shift 2
            ;;
        --) shift ; break
            ;;
        esac
done

if [ -z "$PRINTER" ]; then
   PRINTER=`lpstat -d | sed -e "s/system default destination: //"`
   if [ -z "$PRINTER" ]; then
      echo "No default printer - use  \"-P printer_name\"" > /dev/stderr
      exit 255
   fi
fi

jobs=$*

driver=`lpstat -v $PRINTER | sed -e "s/device for $PRINTER: //"`

status=0
if [ "$jobs" = "-" ]; then
  # remove all jobs for the PRINTER 
     jobs=`lpstat $PRINTER | cut -d\  -f1 | sed -e "s/$PRINTER-//"`
fi
for n in $jobs ; do
  # remove separate job by number
    # first remove job from spool queue
    if lprm-cups -P $PRINTER $n ; then
    # then kill driver of active job if is
       pid=`ps -C $driver --format pid,command`
       pid=`echo $pid | grep "$driver $n "`
       pid=`echo $pid | awk '{print $3}'`
       if [ -n "$pid" ]; then
          sudo kill -9 $pid
       fi
    else
       # lprm-cups is failed, maybe "not owner". 
       # Bad return status, but continue
       status=`expr $status + 1`
    fi
done
exit $status
