#!/bin/sh
# this script inserts some pdfmarks to postscript files to let
# distiller/ghostscript add document info records and notes to 
# PDF files

# check whether we should collect debug messages
if [ ${DEBUG} = TRUE ]; then
        exec 2>>${DEBUG_LOG}
else
        exec 2>/dev/null
fi

echo "$0 - Adding pdfmarks" >&2

case ${FILE_TYPE} in
	PostScript*)

		# add a DOCINFO pdfmark at the end of the file
		
		cat >>"${TMP_FILE}" <<-END-OF-PDFMARK-CODE
		/pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse
		[/Title (${CUPS_JobInfoPMJobName})
		/Author (${CUPS_JobInfoPMJobOwner})
		/Creator (${CUPS_JobInfoPMApplicationName})
		/DOCINFO pdfmark
		END-OF-PDFMARK-CODE

		# if the file has already been converted from
		# PDF to PS then apply a warning on the first
		# page

		if [ ${CONTENT_TYPE} = "application/pdf" ]; then

			# get a temporary filename
			TMP_FILE2=${TMPDIR:=/tmp}/$1_temp_$$
	
			while [ -e "${TMP_FILE2}" ]; do
				TMP_FILE2="${TMP_FILE2}x"
			done

			# Search the line that indicates page 1
			InsertPos=`egrep -n "^%%Page: 1 " "${TMP_FILE}" | cut -d: -f 1`

			# copy the stuff in our new temp file
			head -n ${InsertPos} "${TMP_FILE}" >"${TMP_FILE2}"

			# add the pdfmark code
			cat >>"${TMP_FILE2}" <<-END-OF-PDFMARK-CODE
			/pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse
			[/Rect [75 400 375 500 ]
			/Open true
			/Title (Warning: multiple format conversion occured)
			/Contents (Application created ${CONTENT_TYPE}
			CUPS converted to ${FILE_TYPE}
			Now converted back to PDF 

			This PDF should be handled with care. 
			Especially in prepress environments)
			/Color [1 0 0 ]
			/ANN pdfmark
			END-OF-PDFMARK-CODE

			# and continue with the original ps code
			sed 1,${InsertPos}d "${TMP_FILE}" >>"${TMP_FILE2}"

			# overwrite the orig temp file with the new one
			mv "${TMP_FILE2}" "${TMP_FILE}"

			echo "$0: successfully merged pdfmarks in the PS code" >&2
		fi
		;;
	PDF*)
		echo "$0: PDF file. skipped" >&2
		;;
esac

exit 0

