#!/bin/sh

ATHENA_PRINTERS=
DEFAULT_PRINTER="mitprint"
PRLIST="/var/lib/debathena-cupsys-config.added_printers"

add_printers() {
    rm -f $PRLIST
    lpadmin -p mitprint -E -v lpd://mitprint.mit.edu/bw \
	-D "Pharos (Monochrome)" \
	-L "Release jobs from any Pharos B&W printer" \
	-o printer-is-share=false \
	-m drv:///hpijs.drv/hp-laserjet_9050-hpijs-pcl3.ppd
    if [ $? != 0 ]; then
	echo "FAILED to add Pharos printer $p"
    else
	echo "Added Pharos printer $p"
	echo "$p" >> $PRLIST
    fi
    lpadmin -p mitprint-color -E -v lpd://mitprint.mit.edu/color \
	-D "Pharos (Color)" \
	-L "Release jobs from any Pharos Color printer" \
	-o printer-is-share=false \
	-m drv:///hpijs.drv/hp-color_laserjet_cp3525-hpijs-pcl3.ppd
    if [ $? != 0 ]; then
	echo "FAILED to add Pharos printer $p"
    else
	echo "Added Pharos printer $p"
	echo "$p" >> $PRLIST
    fi
    for a in $ATHENA_PRINTERS; do
        # Don't clobber queue, this is -cluster
	if add-athena-printer $a; then
	    echo "Added Athena printer $a"
	    echo "$p" >> $PRLIST
	else
	    echo "FAILED to add Athena printer $a"
	fi
    done
    # Dear CUPS,  
    # There exist return codes.  Use them.
    # Love, Debathena
    if [ "$(lpstat -d)" = "no system default destination" ]; then
	lpadmin -d $DEFAULT_PRINTER
    fi
    # We don't need to deal with this on uninstall.  CUPS is
    # smart enough (for now, at least) to not retain a default when 
    # the printer in question is deleted.
}

del_printers() {
    # Initially assume we remove nothing and the user can deal
    PRINTERS_TO_REMOVE=
    if [ -s $PRLIST ]; then
        PRINTERS_TO_REMOVE=`cat $PRLIST`
    fi
    for p in $PRINTERS_TO_REMOVE; do
	lpadmin -x $p
	if [ $? != 0 ]; then
	    echo "Failed to remove printer $p!"
	fi
    done
    rm -f $PRLIST
}

require_cups() {
    # Ensure CUPS is running
    [ -e /etc/init.d/cups ] && rcname=cups || rcname=cupsys
    if hash invoke-rc.d; then
        invoke="invoke-rc.d $rcname"
    else
        invoke="/etc/init.d/$rcname"
    fi
    if ! /etc/init.d/$rcname status; then
	if ! $invoke start; then
	    echo "FATAL: Couldn't start CUPS!"
	    exit 1
	fi
    fi
    if [ "$(lpstat -r)" != "scheduler is running" ]; then
      echo "FATAL: cups claimed to have started, but lpstat -r says it's not running!"
      exit 1
    fi
}

case "$1" in
    add)
	require_cups  
	add_printers
	;;
    remove)
	require_cups
	del_printers
	;;
    *)
	echo "Usage: $0 [ add | remove ]"
	exit 1
	;;
esac
exit 0
