#!/bin/bash
#
# Build the Booke. Move subfiles into place and build the Booke into a PDF.
#
# The Booke tune content and all EPS and PDF tune graphics must be
# present already. Run makeGraphics.sh first and then
# makeBookeTunePages.sh.
#

if [ $# -lt 2 ]; then
    echo "Usage: makeBooke.sh <A4|A5> <book dir name> [<book dir name>...]"
    exit 1
fi

dir=`pwd`

builddir=$dir/build
booketex=$builddir/dottes.tex
bookepdf=$builddir/dottes.pdf
usecompact=""

if [ "$1" = "--use-compact" ]; then
    usecompact="yes"
    shift
fi

papersize=$1
shift

mkdir -p $builddir

if [ $# -eq 1 ]; then
    bookename=$1
    for item in title subtitle instrument
    do
        rm -f $builddir/$item.txt
        if [ -r $1/$item.txt ]; then
            cp $dir/$1/$item.txt $builddir/$item.txt
        else
            touch $builddir/$item.txt
        fi
    done
else
    bookename="Bumper"
    echo "The Bumper Booke" > $builddir/title.txt
    echo "The collected Bookes of Dottes" > $builddir/subtitle.txt
    rm -f $builddir/instrument.txt
    if [ -r $1/instrument.txt ]; then
        cp $1/instrument.txt $builddir/instrument.txt
    else
        touch $builddir/instrument.txt
    fi
fi

cp dottes.tex $builddir
cp buildno.txt $builddir
cp buzzard.pdf $builddir

rm -f $builddir/tunes.tex
rm -f $builddir/firstlines.tex

while [ $# -gt 0 ]
do
    section=$dir/$1
    # Section name - strip any instrument name off the end.
    sectionname=${1/-*/}

    for item in title.txt subtitle.txt instrument.txt image.jpg
    do
        rm -f $builddir/$1-$item
        if [ -r $section/$item ]; then
            cp $section/$item $builddir/$1-$item
        else
            touch $builddir/$1-$item
        fi
    done
    for item in intro
    do
        rm -f $builddir/$1-$item.tex
        if [ -r $section/$item.md ]; then
            pandoc --from=markdown --to=latex --output=$builddir/$1-$item.tex $section/$item.md
        else
            touch $builddir/$1-$item.tex
        fi
    done

    sed -e "s/@SECTION@/$1/" -e "s/@SECTIONNAME@/$sectionname/" dottes.tex.section-tunes >> $builddir/tunes.tex
    sed -e "s/@SECTION@/$1/" -e "s/@SECTIONNAME@/$sectionname/" dottes.tex.section-firstlines >> $builddir/firstlines.tex

    shift
done

for filename in $dir/*.${papersize}.tex
do
    name=`basename $filename .${papersize}.tex`
    cp $filename $builddir/$name.tex
done

cd $builddir

xelatex $booketex
xelatex $booketex
xelatex $booketex

mv $bookepdf $dir/$bookename-${papersize}.pdf

cd $dir
