#!/bin/bash

# Pre-commit hook to compile LaTeX files and generate cv.webp

set -e  # Exit on error

# Function to compile LaTeX file
compile_latex() {
    local texfile=$1
    local pdffile="${texfile%.tex}.pdf"

    echo "Compiling $texfile..."

    # Run pdflatex twice to resolve references
    pdflatex -interaction=nonstopmode "$texfile" > /tmp/latex_output.log 2>&1
    pdflatex -interaction=nonstopmode "$texfile" > /tmp/latex_output.log 2>&1

    # Check if PDF was created successfully (ignore exit code as warnings cause non-zero)
    if [ -f "$pdffile" ]; then
        echo "✓ Successfully compiled $pdffile"
        return 0
    else
        echo "✗ Failed to compile $texfile"
        echo "See /tmp/latex_output.log for details"
        return 1
    fi
}

# Function to generate webp from PDF
generate_webp() {
    local pdffile=$1

    echo "Generating cv.webp from $pdffile..."

    # Use pdftoppm to convert first page to PNG, then ImageMagick to convert to WebP
    pdftoppm -png -f 1 -l 1 -singlefile "$pdffile" temp_cv && \
    magick temp_cv.png -quality 85 img/cv.webp && \
    rm -f temp_cv.png

    if [ $? -eq 0 ]; then
        echo "✓ Successfully generated img/cv.webp"
        git add img/cv.webp
        return 0
    else
        echo "✗ Failed to generate cv.webp"
        return 1
    fi
}

# Check if .tex files are staged or modified
if git diff --cached --name-only | grep -qE "^cv(_de)?\.tex$" || \
   [ -f "cv.tex" -a "cv.tex" -nt "cv.pdf" ] || \
   [ -f "cv_de.tex" -a "cv_de.tex" -nt "cv_de.pdf" ]; then

    echo "==== Compiling LaTeX files ===="

    # Compile cv.tex if it exists and is newer than PDF or staged
    if [ -f "cv.tex" ]; then
        if [ ! -f "cv.pdf" ] || [ "cv.tex" -nt "cv.pdf" ] || \
           git diff --cached --name-only | grep -q "^cv\.tex$"; then
            compile_latex "cv.tex" || exit 1
        fi
    fi

    # Compile cv_de.tex if it exists and is newer than PDF or staged
    if [ -f "cv_de.tex" ]; then
        if [ ! -f "cv_de.pdf" ] || [ "cv_de.tex" -nt "cv_de.pdf" ] || \
           git diff --cached --name-only | grep -q "^cv_de\.tex$"; then
            compile_latex "cv_de.tex" || exit 1
        fi
    fi

    echo ""
fi

# Generate cv.webp from cv.pdf
if [ -f "cv.pdf" ]; then
    if [ ! -f "img/cv.webp" ] || [ "cv.pdf" -nt "img/cv.webp" ]; then
        echo "==== Generating WebP image ===="
        generate_webp "cv.pdf" || exit 1
    fi
fi

echo ""
echo "==== Pre-commit checks complete ===="

exit 0
