#!/bin/bash

set -e

if [[ ! -f "main.tex" ]]; then
    echo "No main.tex found." > /dev/fd/2
    exit 1
fi
if [[ ! -f "bibliography.bib" ]]; then
    echo "No bibliography.bib found." > /dev/fd/2
    exit 2
fi

mkdir -p obj
cp -u main.tex obj/
cp -u bibliography.bib obj/
truncate -s 0 obj/uses.tex
[[ -f "title.tex" ]] && cp -u title.tex obj/title.tex

for file in $(find src/ -name "*.md"); do
    target="$(dirname "$file")/$(basename "$file" .md).tex"
    mkdir -p "obj/$(dirname "$target")"
    echo "\\input{$target}" >> obj/uses.tex
    echo "Build MD $file"
    pandoc -i "$file" -o "obj/$target"

    # copy images if needed
    for img in $(grep -oP '\\includegraphics[^{]*{\K[^}]*(?=})' "obj/$target"); do
        img="$(dirname "$file")/$img"
        mkdir -p "$(dirname "obj/$img")"
        cp -u "$img" "obj/$img"
    done
done

pushd obj > /dev/null
echo "Build PDF (1/2)"
latexmk -pdf -interaction=nonstopmode -file-line-error main.tex
echo "Build PDF (2/2)"
latexmk -pdf -interaction=nonstopmode -file-line-error main.tex
popd > /dev/null

mkdir -p bin
cp -u obj/main.pdf bin/main.pdf
