#!/bin/sh
# -------------------------------------------------------------------
# "/usr/lib/cups/backend/pdf":
# -------------------------------------------------------------------
#
PDFBIN=/usr/lib/cups/pdf/ps2pdf.cups
MAILBIN=/usr/lib/cups/pdf/sendpdf
FILENAME=

# filename of the PDF File
PRINTTIME=`date +%Y-%m-%d_%H.%M.%S`

# no argument, prints available URIs
if [ $# -eq 0 ]; then
  if [ ! -x "$PDFBIN" ]; then
    exit 0
  fi
  echo "direct pdf \"Unknown\" \"PDF Creator\""
  exit 0
fi

# case of wrong number of arguments
if [ $# -ne 5 -a $# -ne 6 ]; then
  echo "Usage: pdf job-id user title copies options [file]"
  exit 1
fi

# get PDF directory from device URI, and check write status
PDFDIR=${DEVICE_URI#pdf:}
if [ ! -d "$PDFDIR" -o ! -w "$PDFDIR" ]; then
  echo "ERROR: directory $PDFDIR not writable"
  exit 1
fi

# generate output filename
OUTPUTFILENAME=
if [ "$3" = "" ]; then
  OUTPUTFILENAME="$PDFDIR/unknown.pdf"
else
  if [ "$2" != "" ]; then
    OUTPUTFILENAME="$PDFDIR/$2-$PRINTTIME.pdf"
  else
    OUTPUTFILENAME="$PDFDIR/$PRINTTIME.pdf"
  fi
fi

# run ghostscript
if [ $# -eq 6 ]; then
  $PDFBIN $6 $OUTPUTFILENAME >& /dev/null
else
  $PDFBIN - $OUTPUTFILENAME >& /dev/null
fi

# Make the file visible (but read-only except for owner);
# This is only needed when the username ($2) is not set,
# for instance when printing a test page from the web interface.
chmod 644 $OUTPUTFILENAME

## Normally the PDF file will be emailed to the creating user.
## Alternatively, you can decide not to email it,
## but leave the file on the server and restrict access by others:
if [ "$2" != "" ]; then
  $MAILBIN $2 $OUTPUTFILENAME
  rm -f $OUTPUTFILENAME
fi
#if [ "$2" != "" ]; then
#       chown $2 $OUTPUTFILENAME
#       chmod 700 $OUTPUTFILENAME
#fi
exit 0
