#!/bin/bash

set -e

echo "Starting batch processing of .tex files in chapters/ directory"
echo "==============================================================="

total_files=$(find chapters -name "*.tex" -type f | wc -l)
processed_files=0

if [ $total_files -eq 0 ]; then
    echo "No .tex files found in chapters/ directory"
    exit 0
fi

echo "Found $total_files .tex file(s) to process"
echo ""

for texfile in chapters/*.tex; do
    if [ -f "$texfile" ]; then
        processed_files=$((processed_files + 1))
        base="${texfile%.*}"
        filename=$(basename "$texfile")

        echo "[$processed_files/$total_files] Processing: $filename"
        echo "  └─ Running biber on $base..."
        if biber "$base" 2>&1 | tee -a "$base.biber.log"; then
            echo "  └─ Biber completed successfully"
        else
            echo "  └─ ERROR: Biber failed for $filename"
            echo "     Check $base.biber.log for details"
            exit 1
        fi

        echo "  └─ Running pdflatex on $filename..."
        if pdflatex -interaction=nonstopmode "$texfile" 2>&1 | tee -a "$base.pdflatex.log"; then
            echo "  └─ pdflatex completed successfully"
        else
            echo "  └─ ERROR: pdflatex failed for $filename"
            echo "     Check $base.pdflatex.log for details"
            exit 1
        fi

        echo "  └─ Finished processing $filename"
        echo ""
    fi
done

echo "==============================================================="
echo "Batch processing complete: Successfully processed $processed_files/$total_files file(s)"
