#!/bin/bash

export PATH="/usr/sbin:/usr/bin:$PATH"

SOURCE_DIR=$(pwd)
PARENT_DIR=$(dirname "$SOURCE_DIR")
CHAPTER_NAME=$(basename "$SOURCE_DIR")

run_lualatex() {
    local jobname=$1
    local texinput=$2
    local passes=${3:-2}

    local tmpdir=$(mktemp -d)

    mkdir -p "$tmpdir/$CHAPTER_NAME"
    ln -s "$SOURCE_DIR/main.tex" "$tmpdir/$CHAPTER_NAME/main.tex"
    [ -d "$SOURCE_DIR/media" ] && ln -s "$SOURCE_DIR/media" "$tmpdir/$CHAPTER_NAME/media"
    [ -d "$SOURCE_DIR/libs" ] && ln -s "$SOURCE_DIR/libs" "$tmpdir/$CHAPTER_NAME/libs"
    [ -d "$PARENT_DIR/libs" ] && [ ! -e "$tmpdir/$CHAPTER_NAME/libs" ] && ln -s "$PARENT_DIR/libs" "$tmpdir/$CHAPTER_NAME/libs"
    [ -d "$SOURCE_DIR/fonts" ] && ln -s "$SOURCE_DIR/fonts" "$tmpdir/$CHAPTER_NAME/fonts"
    [ -d "$PARENT_DIR/fonts" ] && [ ! -e "$tmpdir/$CHAPTER_NAME/fonts" ] && ln -s "$PARENT_DIR/fonts" "$tmpdir/$CHAPTER_NAME/fonts"

    cd "$tmpdir/$CHAPTER_NAME"

    echo "[START] $jobname"
    for ((i=1; i<=passes; i++)); do
        lualatex -interaction=nonstopmode -jobname="$jobname" -shell-escape "$texinput" > "$tmpdir/$jobname.log" 2>&1
    done

    if [ ! -f "$jobname.pdf" ]; then
        echo "[ERROR] $jobname failed - no PDF produced"
        tail -20 "$tmpdir/$jobname.log" 2>/dev/null
        rm -rf "$tmpdir"
        return 1
    fi

    cp "$jobname.pdf" "$SOURCE_DIR/"
    echo "[DONE]  $jobname"

    cd "$SOURCE_DIR"
    rm -rf "$tmpdir"
}

run_lualatex "$CHAPTER_NAME" "\PassOptionsToClass{handout}{beamer}\input{main.tex}" 3 &
pid1=$!
run_lualatex "$CHAPTER_NAME-presentation" "main.tex" 3 &
pid2=$!
run_lualatex "$CHAPTER_NAME-print-portrait" "\PassOptionsToClass{handout}{beamer}\def\printportrait{1}\input{main.tex}" 3 &
pid3=$!
run_lualatex "$CHAPTER_NAME-print-landscape" "\PassOptionsToClass{handout}{beamer}\def\printlandscape{1}\input{main.tex}" 3 &
pid4=$!

failed=0
for pid in $pid1 $pid2 $pid3 $pid4; do
    wait $pid || failed=1
done

if [ $failed -eq 1 ]; then
    echo "Some compilations failed."
    exit 1
fi

echo "All compilations complete."
