#!/bin/bash

set -e

BasePath=$(pwd)

LANGS="en_US"

noweave -index -delay BuildWithGBP.nw > BuildWithGBP.tex # contains preamble
noweave -index -delay Title.nw > GBP-Title.tex
noweave -index -delay Part1.nw > GBP-Part1.tex
noweave -index -delay Part2.nw > GBP-Part2.tex
noweave -index -delay Part3.nw > GBP-Part3.tex
noweave -index -delay Part4.nw > GBP-Part4.tex
noweave -index -delay Part5.nw > GBP-Part5.tex
noweave -index -delay Part6.nw > GBP-Part6.tex

#noweave -filter l2h -index -html BuildWithGBP.nw | htmltoc > BuildWithGBP.html

#if [ -f BuildWithGBP.aux ]
#then
    #rm BuildWithGBP.aux
#fi

for ((i=4; i>0; i--))
do
    echo $i
    pdflatex -shell-escape BuildWithGBP.tex

    # Create Index only one time
    # Otherwise you get wrong page numbers
    if [ i=4 ]
    then
        makeindex BuildWithGBP
     fi

    # Create Bibliography
    biber BuildWithGBP
done
# tex4ebook -f mobi BuildWithGBP.tex
# tex4ebook -f epub BuildWithGBP.tex ../

if ls | grep --quiet '\.html'
then
    rm *.html
fi

#For the first translation

for lang in ${LANGS}
do
    cd translation/${lang}/target
    #sed --in-place --expression 's/^%+-.*//' GBP-Part3.tex
    sed --in-place --expression ':a;N;$!ba;s/_ \n\n%/_%/' GBP-Part3.tex

    if [ -f BuildWithGBP.aux ]
    then
        rm BuildWithGBP.aux
    fi

    for ((i=4; i>0; i--))
    do
        pdflatex -shell-escape ./BuildWithGBP.tex
        if [ i=4 ]
        then
            makeindex BuildWithGBP
        fi

        # Create Bibliography
        biber BuildWithGBP
    done
#    tex4ebook -f epub BuildWithGBP.tex ../

    #if ls | grep --quiet '\.html'
    #then
        #rm *.html
    #fi

    cd ${BasePath}
done

# Remove auxillary *.html files which are needed for epub
