#!/bin/bash

# adjust to paths for pdfinfo (from the xpdf package, which I got from
# fink.sourceforge.net) and pdflatex (from the teTeX package, which I
# got from ii2.sourceforge.net, though fink has it as well). Uses the
# pdfpages TeX package, but that should be included with teTeX. If
# not, ctan.org has it.
pdfinfo="/opt/local/bin/pdfinfo"
pdflatex="/usr/texbin/pdflatex"
pdfcrop="/usr/texbin/pdfcrop"
# 3RD argument when PDF Services calls this script is the full path of
# the PDF file to process
infile="$1"

# temporary directory tied to the script's unique process ID
tmpdir="/tmp/$$"


#echo "$tmpdir"

# remove temporary files and directories when we exit for any reason.
# As per Apple's sample at www.apple.com/applescript/print, the
# *parent* directory of the input file is deleted on completion.
 onexit() {
	sleep 5
	rm -rf "$tmpdir"		# Deletes temp directory and anything in it
	rmdir "${infile%/*}"	# Parent directory is only removed if empty
 }    
 trap onexit EXIT

# put input file into new working directory -- renamed without spaces,
# as files and paths with spaces in them make TeX unhappy
 mkdir "$tmpdir"
 
 #pdfcrop "$infile" "$tmpdir/in.pdf"
 cp "$infile" "$tmpdir/in.pdf"
 cd "$tmpdir"

# pdfcrop "$tmpdir/in.pdf" "$tmpdir/out.pdf"
#echo "$1"
#cp "$infile" "in.pdf"

# get page count, rounded up to the nearest 4
pages=$("$pdfinfo" "$infile" | awk '/^Pages/{print $2+3 - ($2+3)%4;}')

# create single fold booklet form in the working directory
"$pdflatex" -interaction=batchmode \
'\documentclass{book}\
\usepackage{pdfpages}\
\begin{document}\
  \includepdf[pages=-,signature='$pages',landscape]{'"$tmpdir/in.pdf"'}\
\end{document}' 2>&1 >/dev/null

#rm "book.aux"
#rm "book.log"

#echo $PWD


# reopen in Preview. Can save, print duplex or print odd then even
# (manual duplex) from there
open -a Preview book.pdf

