#!/bin/bash
#
# Build the website. The common items and the web items are assumed
# to be already built. This generates the MusicXML and the page HTML
# and shuffles other files ino the right place.
#

#set -x

if [ $# -lt 2 -o $# -gt 3 ]; then
    echo "Usage: makeWeb.sh <book dir name> <master book dir name> [<instrument name>]"
    exit 1
fi

dir=`pwd`

booke=$1
masterbooke=$2
bookedir=$dir/$1
masterbookedir=$dir/$2
webdir=$dir/web/$1
graphicsdir=$dir/graphics/$1
output=index.html
tunelist=tunelist.html
title=$booke
instrument=$3
abc2xml=$dir/abc2xml/abc2xml.py

buildno=`cat buildno.txt`
# Remove trailing % added for Latex purposes.
buildno=${buildno%%%}
subtitle=
intro=
if [ -r $bookedir/subtitle.txt ]; then
    subtitle=`cat $bookedir/subtitle.txt`
fi

if [ -n "$instrument" ]; then
    title="${title} ($instrument)"
    subtitle="${subtitle} ($instrument)"
fi

mkdir -p $webdir

sed -e "s/@BUILD@/$buildno/" -e "s/@SUBTITLE@/$subtitle/" \
    -e "s/@TITLE@/$title/" -e "s/@BOOK@/$booke/" dottes.html > $webdir/$output

for item in intro
do
    rm -f $webdir/$item.html
    if [ -r $booke/$item.md ]; then
        pandoc --from=markdown --to=html --output=$webdir/$item.html $booke/$item.md
    else
        touch $webdir/$item.html
    fi
done

# Copy in the book PDFs. Like the graphics, Midi etc. these are assumed
# to be already generated.
cp $1-*.pdf $webdir

# Now, for each tune, make the tune page.
rm -f $webdir/$tunelist
find $bookedir -name "*.abc" | sort |
    while read filename
    do
        name=`basename $filename .abc`

        # Copy the ABC into the web.
        cp $filename $webdir

        # Generate MusicXML into the web.
        python $abc2xml $filename > ${webdir}/${name}.xml

        # If we are not the master booke, link the mp3s in from the
        # master page in a desperate attempt to make IE8 work.
        # The Jenkins archive will dereference the soft link, it seems,
        # but I guess I can live with copies of the MP3 for now.
        if [ "$booke" != "$masterbooke" ]; then
            pushd ${webdir} > /dev/null
            ln -f -s ../${masterbooke}/*${name}.mp3 .
            popd > /dev/null
        fi

        # Get date and time of last change to tune.
        lastchanged=`hg log --limit 1 --template "{date|shortdate}" $masterbookedir/${name}.abc`

        # Generate the tune web page.
        tunepage=${name}.html
        learnerpage=learner-${name}.html

        $dir/abctemplate.py --value "masterbooke=${masterbooke}" --value "lastchanged=${lastchanged}" --template dottes.html.tune $filename > $webdir/$tunepage
        $dir/abctemplate.py --value "masterbooke=${masterbooke}" --value "lastchanged=${lastchanged}" --template dottes.html.learnertune $filename > $webdir/$learnerpage
        $dir/abctemplate.py --template dottes.html.tuneindex $filename >> $webdir/$tunelist
    done
