#!/bin/bash
# Wrapper script for cups pstops filter.
# Adds support for font embedding
# Could be used with vendor provided PPD's
#
# 2002/11/26 v0.1 <yurix@unixcenter.ru>

LOGFILE=/tmp/pstops-wrapper.log
REALFILTER=/usr/lib/cups/filter/pstops
TEMPFILE=/tmp/pstops-wrapper.temp.file
PSwrite="/usr/bin/gs -q -dPARANOIDSAFER -dNOPAUSE -dBATCH -sDEVICE=pswrite \
					  -dLanguageLevel=2 -sOutputFile="
PDFwrite="/usr/bin/gs -q -dPARANOIDSAFER -dNOPAUSE -dBATCH -sDEVICE=pdfwrite \
					  -dPDFSETTINGS=/printer -sPAPERSIZE=a4 \
					  -dEmbedAllFonts=true -dSubsetFonts=true \
					  -sOutputFile="
PDFtoPS="/usr/lib/cups/filter/pdftops"

debug()
{
  echo "`/bin/date` pstops-wrapper: $*" >> $LOGFILE
}

ParseEmbedOpt()
{
# returns
#  0 if user supply no option regarding font embedding
#  1 if user choose to enable font embedding
#  2 if user choose to disable font embedding

# We should support current boolean options syntax style (Opt=true/false), as well as old one
# (Val, noVal)  
echo $1 | sed -e "s/\([^[:blank:]]*[[:blank:]]\)*\([^[:blank:]]*\)\(EmbedFonts\)\([^[:blank:]]*\).*\$/-\2 -\3 -\4/" \
| while read -a n;  do
  if [ "${n[1]}" = "-EmbedFonts" ]; then
	if [ "${n[0]}" = "-no" -o "${n[2]}" = "-=False" ]; then
	  return 2
	else
	  return 1
	fi
  fi
done;
}

# though it's not nessasary, just for the case, cut off our options
# to stop fooling REALFILTER and printer's PS interpreter. 
cleanoptions=`echo $5 | sed -e s/[^[:blank:]]*EmbedFonts[^[:blank:]]*//`

ParseEmbedOpt "$5"; UserEmbedReq=$?

debug "id $1, $2-$3, " $5

if [ "$6" = "" ]; then
	file="-"
else
	file="$6";
##	debug "We're first in stack because we got job filename: $file"
fi

PASS_CMD="cat $file"	

# GS's ps2ps produce vary messy output 
EMBED_CMD_GSPS="$PSWRITE- $file"
# Calling pdf2ps first seems to give better result.
# For some reason two gs are failing when they run though pipe
# so we have to use temporary file. (?)
EMBED_CMD_GSPDFPS="$PDFwrite$TEMPFILE $file; $PSwrite- $TEMPFILE"
# It seems like best is to call cups pdftops filter
#EMBED_CMD_GSPDF_CUPSPS="$PDFwrite- $file | $PDFtoPS $1 $2 \"$3\" $4 none"
EMBED_CMD_GSPDF_CUPSPS="$PDFwrite- $file | $PDFtoPS 0 none none 1 none"
# finaly choose font embedding method
EMBED_CMD=$EMBED_CMD_GSPDF_CUPSPS					  


# Do embedding according CUPS_EMBEDFONTS variable. Any user options should
# override default policy
case "$CUPS_EMBEDFONTS" in
	True|true|Yes|yes|1)
						if [ $UserEmbedReq -eq 2 ]; then
						  EMBED=$PASS_CMD;
					  	  debug "Font embedding disabled by user"
						else
						  EMBED=$EMBED_CMD
						fi
						;;
					  *)
						if [ $UserEmbedReq -eq 1 ]; then
						  EMBED=$EMBED_CMD;
					  	  debug "Font embedding requested by user"
						else
						  EMBED=$PASS_CMD
						fi
esac

# Embed fonts and pass the result to ps2ps filter
##debug "pstopsopts:" $cleanoptions
eval $EMBED | $REALFILTER $1 $2 $3 $4 "$cleanoptions"

# remove temp file, if needed
if [ -f $TEMPFILE ]; then
  rm -f $TEMPFILE
fi

