#!/bin/sh
# -------------------------------------------------------------------
# "/usr/lib/cups/backend/pdf":
# -------------------------------------------------------------------
#
FILENAME=
# filename of the PDF File
PRINTTIME=`date +%Y-%m-%d_%H.%M.%S`
# case of wrong number of arguments
if [ $# -ne 5 -a $# -ne 6 ]; then
  echo "Usage: ecodms job-id user title copies options [file]"
  exit 1
fi
# check for username and title to be present
if [ "$2" = "" -o "$3" = "" ]; then
   echo "ERROR: username and title must be set - maybe you are trying to print not from the X session" 1>&2 
   exit 1
fi
# check if there is a ecodmssinglesignon process for the current user
MYUID=`id -u $2`
DBUSPROC=`ps -eo euid,ruid,pid,comm,args | grep ecodmssinglesignon | grep -v grep | grep $MYUID | awk '{print \$1}'`
if [ "$MYUID" != "$DBUSPROC" ]; then
   echo "ERROR: There is no or more then one ecodmssinglesignon process running on the machine for user $2" 1>&2
   exit 1
fi
# get PDF directory from device URI, and check write status
PDFDIR=${DEVICE_URI#ecodms:}
if [ ! -d "$PDFDIR" -o ! -w "$PDFDIR" ]; then
  echo "ERROR: directory $PDFDIR not writable"
  exit 1
fi
# generate output filename
OUTPUTFILENAME="$PDFDIR/$2-$1-$PRINTTIME.ps"
# set input filename if any
INPUTFILENAMEOPTION=-
if [ $# -eq 6 ]; then
  INPUTFILENAMEOPTION=-f $6
fi
#run ghostscript
#/usr/bin/gs -q -dCompatibilityLevel=1.4 -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pdfwrite -sOutputFile="$OUTPUTFILENAME" -dAutoRotatePages=/PageByPage -dAutoFilterColorImages=false -dColorImageFilter=/FlateEncode -dPDFSETTINGS=/prepress -c .setpdfwrite $INPUTFILENAMEOPTION 
cat $INPUTFILENAMEOPTION > $OUTPUTFILENAME
RC=$?
if [ $RC -ne 0 ]; then
   echo "ERROR: unable to convert the file to pdf format" 1>&2
   exit $RC
fi

# Make the file visible and writable because it should be deleted by the ecodms process;
chmod 666 $OUTPUTFILENAME

echo "ERROR: $OUTPUTFILENAME" 1>&2

## call program here  and perform some cleanup
LD_LIBRARY_PATH=/usr/lib/cups/ecodms/ /usr/lib/cups/ecodms/ecodmsprinter $2 $OUTPUTFILENAME
RC=$?
if [ $RC -ne 0 ]; then
   exit $RC
fi
#TODO: perform some cleanup, e.g. rm -f $OUTPUTFILENAME
exit 0

# EOF
# -------------------------------------------------------------------
