#!/bin/sh
# buildchapter.sh - build just one chapter of the AG manual
# usage: path-to-doc/manual/buildchapter.sh filename
#
# The build happens in a subdirectory so as not to leave turds behind
# that might confuse the main build.
#
# The filename should not have a path on it.
#

if [ $# != 1 ]; then
    echo "Usage: $0 filename" 1>&2
    exit 1
fi

case "$1" in
    /*) echo "$0: filename given with path" 1>&2; exit 1;;
    *.tex) ;;
    *) echo "$0: not a tex file?" 1>&2; exit 1;;
esac

TMPDIR=.pdftmp.$$
SRCDIR=`dirname "$0"`
INPUT="$1"
INPUTBASE=`echo "$INPUT" | sed 's/\.tex$//'`
OUTPUT="$INPUTBASE.pdf"

case "$SRCDIR" in
    /*) ;;
    *) SRCDIR="../$SRCDIR";;
esac

echo '        [MKDIR]   '"$TMPDIR"
mkdir "$TMPDIR" || exit 1
cd "$TMPDIR"

clean() {
    cd ..
    echo '        [RM]      '"$TMPDIR"
    rm -rf "$TMPDIR"
}
trap clean 0 HUP INT TERM

TEXINPUTS=".:${SRCDIR}:"
export TEXINPUTS

for F in agdefs.tex "$INPUT"; do
    echo '        [CP]      '"$F"
    cp "$SRCDIR/$F" . || exit 1
done

echo '        [CREATE]  tmp.tex'
(
    echo '\documentclass{book}'
    echo '\include{agdefs}'
    echo '\begin{document}'
    echo '\include{'"$INPUTBASE"'}'
    echo '\end{document}'
) > tmp.tex

echo '        [LATEX]   tmp.tex'
#pdflatex tmp.tex || exit 1
pdflatex "\\newcommand{\\nohtml}{1}\\input{tmp.tex}"


echo '        [MV]      '"$OUTPUT"
mv -f tmp.pdf ../"$OUTPUT"

# handled by clean()
#cd ..
#rm -rf $TMPDIR
exit 0

