#!/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

function build_success () {
    echo "Build finished. Continue waiting..."
    if which dunstify > /dev/null; then
        dunstify "Build success" -u normal -h string:x-dunst-stack-tag:md-pandoc-build
    fi
}

function build_fail () {
    echo "Build error. Please try again..."
    if which dunstify > /dev/null; then
        dunstify "Build fail" -u critical -h string:x-dunst-stack-tag:md-pandoc-build
    fi
}

if [ "$1" = "watch" ]; then
    if ! which inotifywait > /dev/null; then
        echo "Please install the tool inotifywait to enable watch mode."
        exit 3
    fi

    echo "Waiting for changed file..."
    while inotifywait -qr --event close_write,move,delete --format '%w%f' src; do
        sleep 0.5 # enable to save multiple files at once before build starts
        ./build.sh \
            && build_success \
            || build_fail
    done
    exit 0
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" -or -name "*.tex" | sort); do
    if [ "${file##*.}" = "md" ]; then
        target="$(dirname "$file")/$(basename "$file" .md).tex"
        echo "\\input{$target}" >> obj/uses.tex
        if [ -f "obj/$target" ] && [ ! "$file" -nt "obj/$target" ]; then
            continue
        fi
        mkdir -p "obj/$(dirname "$target")"
        echo "Build MD $file"
        pandoc -i "$file" -o "obj/$target" --highlight-style=haddock
    else
        target="$file"
        mkdir -p "obj/$(dirname "$target")"
        echo "\\input{$target}" >> obj/uses.tex
        echo "Copy TEX $file"
        cp -u "$file" "obj/$target"
    fi

    # 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
    sed -ri "s@(\\includegraphics[^\{]*\{)([^}]*)\}@\1$(dirname "$file")/\2\}@g" "obj/$target"

    prefix="$(basename "$file" | grep -oP "^\d+-")"
    sed -ri "s/(\\\\(hypertarget|label)\{)/\1${prefix}/g; " "obj/$target"
done

if [[ ! -f "obj/preample.tex" ]]; then
    # generate pandoc preample
    echo "Create Preample"
    echo -e "
\`\`\`csharp
Console.WriteLine(\"Hello World\");
\`\`\`

DEF
: def

| a | b |
|-|-|
| a | b |
| a |
| a | b |
" \
        | pandoc -f markdown -t latex --standalone --highlight-style haddock \
        | sed -n '/\\usepackage/,$p' \
        | sed '1,/\\begin{document}/!d' \
        | head -n -1 \
        | sed 's/\\usepackage{xcolor}/\\usepackage[table]{xcolor}/' \
        > obj/preample.tex
fi

rsync -a src/res obj/src/

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

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