#!/bin/bash
#
# latexcompile

if [ $# -eq 2 ]; then
    echo "Usage: build  [--open] [--clean]"
    echo "--open: After the compilation is finished, the compiled pdf will be opened"
    echo "--clean: First, delete the .aux, .log, .... files, then compile"
    echo "The compilation is done in five steps:"
    echo "    1) first pdflatex compilation"
    echo "    2) nomenclature compilation"
    echo "    3) bibtex compilation"
    echo "    4) second pdflatex compilation"
    echo "    5) third pdflatex compilation"
    exit 2
fi

NAME="dizertacka"

if [[ $1 == "--clean" ]] || [[ $1 == "-c" ]] ; then
    rm "$NAME.bbl"
    rm "$NAME.aux"
    rm "$NAME.blg"
    rm "$NAME.toc"
    rm "$NAME.out"
    rm "$NAME.nlo"
    rm "$NAME.lot"
    rm "$NAME.log"
fi

echo -e "Compiling "$NAME".tex\n"
echo -e "If I get stuck, there is an error somewhere!\n"

pdflatex $NAME".tex" 2>/dev/null 1>&2
if [ $? -ne 0 ]; then
    echo "First compilation failed. Check log."
    exit 1
else 
    echo "First pdflatex succesfully completed."
fi

makeindex $NAME".nlo" -s nomencl.ist -o dizertacka.nls2>/dev/null 1>&2
if [ $? -ne 0 ]; then
    echo "Nomenclature failed. Check log."
    exit 1
else 
    echo "Nomenclature succesfully generated."
fi

bibtex $NAME".aux" 2>/dev/null 1>&2
if [ $? -ne 0 ]; then
    echo "Bibtex compilation failed. Check log."
    exit 1
else 
    echo "Bibtex succesfully completed."    
fi
pdflatex $NAME".tex" 2>/dev/null 1>&2

if [ $? -ne 0 ]; then
    echo "Second compilation failed. Check log."
    exit 1
else 
    echo "Second pdflatex succesfully completed."
fi

pdflatex $NAME".tex" 2>/dev/null 1>&2
if [ $? -ne 0 ]; then
    echo "Third compilation failed. Check log."
    exit 1
else
    echo "Third pdflatex succesfully completed."
fi

if [[ $1 == "--open" ]] || [[ $1 == "-o" ]] ; then
    xdg-open "$NAME.pdf"
fi

exit 0
