#!/bin/bash
#
# cups-pdfgen -- PDF Creator for cups-pdf backend
# 08.02.2003, Volker C. Behr
# Exp. Physik V, Uni Wuerzburg
#
# This code may be freely distributed as long as this header
# is preserved.
#
# HISTORY : 
# 03/19/2003 : 0.5    - adapted to work with Gentoo's 'su' command
# 02/16/2003 : 0.4    - change nobody's files to -rw-rw-rw-
# 02/14/2003 : 0.3    - slashes in the title are acceptable now
# 02/13/2003 : 0.2    - several bugfixes and enhanced security
# 02/12/2003 : 0.1    - first beta release
#

CUPSPDFDIR=/var/tmp/cups-pdf/
CUPSPDFALL=$CUPSPDFDIR'all/'
CUPSPDFSPOOL=$CUPSPDFDIR'.spool/'

if [ ! -d "${CUPSPDFDIR}" ]; then mkdir "${CUPSPDFDIR}" -m 755 ; fi        
if [ ! -d "${CUPSPDFSPOOL}" ]; then mkdir "${CUPSPDFSPOOL}" -m 755 ; fi
if [ ! -d "${CUPSPDFALL}" ]; then 
  mkdir "${CUPSPDFALL}" -m 777 ; chown nobody:nogroup "${CUPSPDFALL}" ;
fi

FILE=$(grep -E "^%%Title:" "$1" | head -n 1 |
       sed -e 's/^%%Title: //g' |
       sed -e 's/\ /_/g' |
       sed -e 's/\//_/g' |
       tr -d "\r\n")

CUID=`id -u "$2" 2>/dev/null`
if [ -z $CUID ]; then CUID=-1 ; USER=nobody ; else USER=$2 ; fi

if (( CUID == -1 )); then FILE=`echo -n -e ${CUPSPDFALL}$2'__'${FILE}'.pdf'` ; else 
  if [ ! -d ${CUPSPDFDIR}$2 ]; then 
    mkdir ${CUPSPDFDIR}$2 -m 700 ; chown $2:`id -g $2` ${CUPSPDFDIR}$2 ;  
  fi ;
  FILE=`echo -n -e ${CUPSPDFDIR}$2'/'${FILE}'.pdf'` ; 
fi

SPOOLFILE=${CUPSPDFSPOOL}`echo $1 | cut -d "/" -f 6`
POS_S=`grep -E -n "%\!PS-Adobe" "$1" | cut -d : -f 1 | head -n 1`
POS_E=`grep -E -n "^%%EOF" "$1" | cut -d : -f 1 | tail -n 1`
if [ -z $POS_E ]; then POS_E=`cat "$1" | wc -l`; fi 
rm -f $SPOOLFILE 2>/dev/null
sed $[$POS_E + 1],\$d "$1" | tail -n $[$POS_E - $POS_S + 1] > $SPOOLFILE 
chown $USER $SPOOLFILE
rm -f "$1" 2>/dev/null

rm -f $FILE 2>/dev/null
su - $USER -c "gs -q -dCompatibilityLevel=1.3 -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=$FILE -c save pop -f $SPOOLFILE"
rm -f $SPOOLFILE 2>/dev/null

if (( CUID == -1 )); then chmod 666 $FILE ; fi
