#!/bin/sh
#
# For testing, uncomment the next three to see what's being sent to this script.
#echo $0 $* >/tmp/print
#cat - >> /tmp/print
#exit 1
#
#
# This program is to be installed as a symlink to /opt/local/bin/lp and
# /opt/local/bin/lpr and assumes that /opt/local/bin is ahead of
# /usr/bin in users' $PATH.
#
# The idea is to use the graphical tool whenever possible.
#
# Fri May 19 21:24:04 PDT 2000 - jimmy
# Sat May 20 19:18:49 PDT 2000 deal with laserw hack - jimmy
# Sat May 11 21:24:33 PDT 2002 hacked to work with generic CUPS
# Thu Dec 12 14:32:54 PST 2002 took out several hacks now that gtklpq
# 			       has been fixed/enhanced - jimmy
# Thu Dec 19 17:46:38 PST 2002 - put some hacks back and added -s preservation

CUPS_SERVER=print ; export CUPS_SERVER

# They may have used lp or lpr
PROGRAM=`basename ${0}`
OPTIONS=""
LPOPTIONS=""
# Add a space to make for better sed usage below
CLIOPTS=" ${1+"$@"}"

# find out if quiet option is set before we clobber it.  We'll need it later.
if `echo "${CLIOPTS}" | grep " -s" > /dev/null` ; then
      LPOPTIONS="${LPOPTIONS} -s"
fi


# get rid of -s, -c, -C from the command line options
# This isn't perfect, but it should hold us until gtklp is fixed
CLIOPTS=`echo "$CLIOPTS" | sed -e s/2\-sided/laser\\\/duplex/`
CLIOPTS=`echo "$CLIOPTS" | sed -e s/laserw/laser\\\/wide/`
CLIOPTS=`echo "$CLIOPTS" | sed -e s/\ \-s/\ /g`
CLIOPTS=`echo "$CLIOPTS" | sed -e s/\ \-c/\ /g`
CLIOPTS=`echo "$CLIOPTS" | sed -e s/\ \-C/\ /g`
CLIOPTS=`echo "$CLIOPTS" | sed -e s/duplex=long/sides=two-sided-long-edge/`

# The graphical print program to use.  Honor a user's GLP if set
#GLP="${GLP-gtklp}"
GLP="${GLP-gtklp}"
#GLP=gtklp
#GLP=glp
#GLP=xpp

# deal with people who have LPDEST set to our old printer names
if [ "Q${LPDEST}" = "Qlaserw" ];then
    LPDEST="laser/wide"
fi

if [ "Q${LPDEST}" = "Q2-sided" ];then
    LPDEST="laser/duplex"
fi

# If DISPLAY isn't set or quiet mode is requested, 
# just hand it off to /opt/cups/bin/lp[r]
if [ "Q" = "Q${DISPLAY}" ] || [ "${LPOPTIONS}" = " -s" ];then
    exec /opt/cups/bin/${PROGRAM} ${LPOPTIONS} ${OPTIONS} ${CLIOPTS}
fi

export LPDEST

# Send it off to glp (graphical lp) but watch the return status in case
# the DISPLAY host isn't really running an X server.
#echo ${GLP} ${OPTIONS} ${CLIOPTS} 2>/dev/null
${GLP} ${OPTIONS} ${CLIOPTS} 2>/dev/null
if [ $? -ne 0 ] #if the above failed
  then
    exec /opt/cups/bin/${PROGRAM} ${LPOPTIONS} ${OPTIONS} ${CLIOPTS}
fi

