#!/bin/bash

# Script written by Thomas Fischer <fischer@unix-ag.uni-kl.de>
# Released under the GNU Public License Version 2
# Last updated: 12 May 2008

export LC_ALL=en_US.utf8
export LANG=C

# initialize variables
packageoptions="absolute"
printhelp=0
outputfile=""
inputfile=""
text=""
textfirstpage=""
width=19
xpos=1
ypos=3
prefixfile=""
first=0

# parse command line parameters
while getopts "hlfx:y:w:t:o:i:p:" flag ; do
	case $flag in
	"p") prefixfile="$OPTARG" ;;
	"h") printhelp=1 ;;
	"l") packageoptions="${packageoptions},overlay" ;;
	"f") first=1 ;;
	"x") xpos=$OPTARG ;;
	"y") ypos=$OPTARG ;;
	"w") width=$OPTARG ;;
	"t") inserted="$(echo "$OPTARG" | sed -e 's/%p/{\\thepage}/g;s/%d/{'"$(date '+%Y-%m-%d~%k:%M')"'}/g')"
	     if [ ${first} -eq 0 ] ; then
	         text="${text}"'\begin{textblock}{'"$width"'}('"$xpos"','"$ypos"')\centering{}'"$inserted"'\end{textblock}'
	     else
	         textfirstpage="${text}"'\begin{textblock}{'"$width"'}('"$xpos"','"$ypos"')\centering{}'"$inserted"'\end{textblock}'
	     fi
	     first=0
	     ;;
	"o") outputfile="$OPTARG" ;;
	"i") inputfile="$OPTARG" ;;
	*) printhelp=1 ;;
	esac
done

if [ $# -eq 0 ] ; then
	printhelp=1
fi

# print help if required
if [ $printhelp -eq 1 ] ; then
	echo "textonpdf.sh  by Thomas Fischer <fischer@unix-ag.uni-kl.de>  last updated 12 May 2008" >&2
	echo "Parameters:" >&2
	echo "   -h               Print this help" >&2
	echo "   -l               Put everything in overlay" >&2
	echo " Box paramters (multiple boxes allowed):" >&2
	echo "   -f               Put box on first page only" >&2
	echo "   -x               Left coordinate in cm" >&2
	echo "   -y               Top coordinate in cm" >&2
	echo "   -w               Width in cm" >&2
	echo "   -t               Text to be put in box" >&2
	echo "                     %p will be replaced by page number" >&2
	echo "                     %d will be replaced by date/time" >&2
	echo " I/O parameters:" >&2
	echo "   -p prefixfile    Put content of this file in header of tex file" >&2
	echo "   -i infile        Input pdf file" >&2
	echo "   -o outfile       Write resulting pdf in outfile (optional)" >&2
	echo "                    If not provided, infile's name will be extended by \"textonpdf\"" >&2
	echo >&2
	echo " Example writes date in header and page number in footer (size A4):" >&2
	echo "   textonpdf.sh -x 5 -w 11 -y 27 -t '%p' -x 1 -w 19 -y 2 -t \"Draft from %d\" -i file.pdf" >&2
	exit 1
fi

# check for auxiliary programs, valid LaTeX system and required packages
which pdfinfo >/dev/null || { echo "pdfinfo must be installed" ; exit 1 ; }
which pdflatex >/dev/null || { echo "pdflatex must be installed" ; exit 1 ; }
kpsewhich textpos.sty >/dev/null || { echo "textpos.sty must be installed in your LaTeX system" ; exit 1 ; }
kpsewhich pdfpages.sty >/dev/null || { echo "pdfpages.sty must be installed in your LaTeX system" ; exit 1 ; }


# check input file (existence)
if [ ! -s "$inputfile" ] ; then
	echo "File \"$inputfile\" does not exist" >&2
	exit 1
fi

# check prefix file (existence)
if [[ -n "$prefixfile" && ! -s "$prefixfile" ]] ; then
	echo "File \"$prefixfile\" does not exist" >&2
	exit 1
fi

# check input file (validity)
numpages=$(pdfinfo "$inputfile" | awk '/^Pages: / {print $2}')
if [ ${numpages}0 -lt 10 ] ; then
	echo "Cannot determine number of pages in pdf file" >&2
	exit 1
fi

# determine output filename
if [ -z "$outputfile" ] ; then outputfile="${inputfile/.pdf/-textonpdf.pdf}" ; fi

# prepare working directory
tmpdir=$(mktemp -d)
mkdir -p ${tmpdir}
cp -p "${inputfile}" "${tmpdir}/input.pdf"

# write intermediate tex file for pdflatex
cat <<EOF >${tmpdir}/pages.tex
\documentclass[a4paper,12pt]{article}
\usepackage{pdfpages}
EOF
echo '\usepackage['"${packageoptions}"']{textpos}' >>${tmpdir}/pages.tex
if [[ -n "$prefixfile" && -s "$prefixfile" ]] ; then
	cat "$prefixfile" >>${tmpdir}/pages.tex
fi
cat <<EOF >>${tmpdir}/pages.tex
\setlength{\TPHorizModule}{1cm}
\setlength{\TPVertModule}{1cm}
\begin{document}
EOF
for n in $(seq 1 $numpages) ; do
	if [ $n -eq 1 ] ; then
		echo -n "${textfirstpage}"
	fi
	echo "$text"'\includepdf[fitpaper=true,pages='$n']{input.pdf}\clearpage'
done >>${tmpdir}/pages.tex
cat <<EOF >>${tmpdir}/pages.tex
\end{document}
EOF

# run pdflatex to create output file
( cd ${tmpdir} ; pdflatex -halt-on-error pages && pdflatex -halt-on-error pages )

# check resulting pdf file
if [ -s "${tmpdir}/pages.pdf" ] ; then
	cp -p "${tmpdir}/pages.pdf" "${outputfile}" && echo "Everything seems to be ok, output is \"${outputfile}\""
else
	rm -rf "${tmpdir}"
	echo "Generating pdf output failed" >&2
	exit 1
fi

# clean up mess
rm -rf "${tmpdir}"
