#!/bin/sh
# Scriptname:       auto_printer_state.sh
# Intention:        monitor the syslog file for the connect/disconnect messages of a usb-printer
#                   and start/stop the printer in cups after finding such a message
#
#                   Since newer Cups versions do this automatically this is only useful for
#                   use with old Cups versions, e.g. under SuSE 9.0


# show current printer state: lpstat -p {PRINTER_NAME}


###############################################################################
# CONFIGURATION
###############################################################################


# command line interface to syslog
LOGGER="/bin/logger -t auto_printer_state.sh"

# printer name as defined in CUPS
PRINTER="laserjet_col"



#########
# ENABLE
#########

# grep regexp to check for
TRIGGER_ON="^[A-Z][a-z][a-z] [0-9 ][0-9]? [0-9][0-9]:[0-9][0-9]:[0-9][0-9] appserver kernel: printer.c: usblp[0-9]: USB Bidirectional printer dev [0-9]+ if 0 alt 1 proto 2 vid 0x03F0 pid 0x1C17$"

# binary to enable printer
ENABLE="/usr/bin/enable"
#ENABLE="/usr/sbin/lpadmin -h localhost -E -p"

# command to execute if trigger was found
ACTION_ON="$ENABLE $PRINTER"



##########
# DISABLE
##########

# grep regexp to check for
TRIGGER_OFF="^[A-Z][a-z][a-z] [0-9 ][0-9]? [0-9][0-9]:[0-9][0-9]:[0-9][0-9] appserver kernel: usb.c: USB disconnect on device 00:04.2-2 address [0-9]+$"

# binary to disable printer
DISABLE="/usr/bin/disable"

# command to execute if trigger was found
ACTION_OFF="$DISABLE $PRINTER"




###############################################################################
# SCRIPT START
###############################################################################

$LOGGER Script started. Beginning to monitor syslog.

# get filesize of logfile
FILESIZE="$(ls -l /var/log/messages | sed -r 's/^.* ([0-9]+) [A-Z][a-z]{2}.*$/\1/')"

while [ true ]
do
	# delay some seconds
	sleep 5
	
	# get current size of logfile
	CURRENTSIZE="$(ls -l /var/log/messages | sed -r 's/^.* ([0-9]+) [A-Z][a-z]{2}.*$/\1/')"

	# calculate how many bytes are new
	CHANGE="$(echo $CURRENTSIZE-$FILESIZE | bc)"
	
	# set new FILESIZE for next iteration
	FILESIZE=$CURRENTSIZE
	

	# ENABLE: check new bytes for a printer-plugged-in message
	CHECK="$(tail -c$CHANGE /var/log/messages|grep -P "$TRIGGER_ON")"
	
	# if trigger was found do something
	if [ "$CHECK" ]; then
		$LOGGER $PRINTER connection recognized. Running enable command: $ACTION_ON
		$ACTION_ON
		continue
	fi
	
	
	# DISABLE: check new bytes for a printer-plugged-out message
	CHECK="$(tail -c$CHANGE /var/log/messages|grep -P "$TRIGGER_OFF")"
	
	# if trigger was found do something
	if [ "$CHECK" ]; then
		$LOGGER $PRINTER disconnect. Running disable command: $ACTION_OFF
		$ACTION_OFF
		continue
	fi
done


