#!/bin/sh
# updated by rcrsn51 2015-04-10

# backend needs 700 permissions - CUPS security requirement?
# the CUPS install needs the ppd file from ghostscript library

# used to test backend
if [ $# -eq 0 ]; then
    echo 'file pdf-writer:/dev/null "Unknown" "CUPS-PDF"'
    exit 0
fi

USERHOME=$(grep "^$2" /etc/passwd | cut -d: -f6)

LANGUAGE=$(grep ^LANG= /etc/profile | cut -c 6-)
[ -z "$LANGUAGE" ] && LANGUAGE="C"

# maybe needed by Xdialog
export PATH=$PATH:/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/X11R7/bin
export DISPLAY=":0.0"
export LANG=$LANGUAGE
export LC_ALL=$LANGUAGE
export XAUTHORITY=$USERHOME/.Xauthority

PDFNAME=$3".pdf"
[ ${PDFNAME:0:1} != "/" ] && PDFNAME=$USERHOME/$PDFNAME
PDFNAME=$(Xdialog --stdout --title "Save As ..." --fselect "$PDFNAME" 0 0)

[ $? -gt 0 ] && cat - > /dev/null && exit 0 	# to finish the job stream

if [ -f "$PDFNAME" ]; then
  Xdialog --title "CUPS-PDF" --yesno "$PDFNAME exists: Overwrite it?" 0 0
  [ $? -gt 0 ] && cat - > /dev/null && exit 0 
fi
	
ps2pdf - "$PDFNAME"

if [ $? -eq 0 ]; then
  Xdialog --title "CUPS-PDF" --infobox "Created: $PDFNAME" 0 0 3000
  chown $2:$2 "$PDFNAME"
else
  Xdialog --title "CUPS-PDF" --msgbox "Invalid filename: $PDFNAME" 0 0
  cat - > /dev/null && exit 0 
fi

exit 0	# so CUPS knows that the job has completed
