#!/bin/bash -e
#
# Run this script on an ATHENA CLUSTER MACHINE.
#
# Known issues with using this on Athena:
# - You need to install pdftk from Ubuntu (the outland locker is too old)
# - You need to edit /usr/bin/anytopnm to make the BMP match not include
#   *data*, 'cause that doesn't show up

if ! type pdftk >/dev/null 2>&1; then
    echo 'You do not have pdftk installed. Try `sudo aptitude install pdftk`'
    exit 1
fi

if pdftk --version | grep -q "pdftk 1.12 a Handy Tool"; then
    echo 'Your pdftk is too old. Try `sudo aptitude install pdftk`'
    exit 1
fi

if ! type acroread >/dev/null 2>&1; then
    attach -q acro
fi

inputdir="input-$(basename ${1/.zip/})"
outputdir="output-$(basename ${1/.zip/})"
mkdir "$inputdir"
mkdir "$outputdir"

unzip -d "$inputdir" "$1"

for i in "$inputdir"/*/*; do
    cat > convert-stamp.tex << EOF
\\documentclass{article}
\\usepackage{fullpage}
\\addtolength{\\oddsidemargin}{-.8in}
\\addtolength{\\topmargin}{-.8in}
\\thispagestyle{empty}
\\begin{document}
\\noindent \\verb+$i+
\\end{document}
EOF
    pdflatex convert-stamp
    case "$i" in
        *.pdf) ;;
        *) anytopnm < "$i" | pnmtops | ps2pdf - - > "$i".pdf
           i="$i".pdf ;;
    esac
    o="${i/$inputdir/$outputdir}"
    mkdir -p "$(dirname "$o")"
    pdftk "$i" stamp convert-stamp.pdf output "$o"
    acroread -toPostScript -rotateAndCenter -size letter "$o"
done

rm -r "$inputdir"
rm convert-stamp.*
