#!/bin/sh

# Build the standalone pgfplots-autonode examples and indexed manual.  This
# workflow deliberately needs neither CoolProp nor shell escape.

set -eu

fail()
{
    printf 'error: %s\n' "$*" >&2
    exit 1
}

need_command()
{
    command -v "$1" >/dev/null 2>&1 \
        || fail "required command not found: $1"
}

for command_name in awk context cp dirname grep lualatex luatex makeindex \
    mkdir mv rm sed tail; do
    need_command "$command_name"
done
SCRIPT_DIR=$(CDPATH= cd -P "$(dirname "$0")" && pwd) \
    || fail "could not determine the script directory"
PROJECT_DIR=$(CDPATH= cd -P "$SCRIPT_DIR/.." && pwd) \
    || fail "could not determine the project directory"
VERSION_FILE=$PROJECT_DIR/PGFPLOTS-AUTONODE-VERSION
[ -f "$VERSION_FILE" ] || VERSION_FILE=$PROJECT_DIR/VERSION
[ -f "$VERSION_FILE" ] || fail "release metadata not found: $VERSION_FILE"

if [ -z "${SOURCE_DATE_EPOCH:-}" ]; then
    SOURCE_DATE_EPOCH=$(sed -n 's/^SOURCE_DATE_EPOCH=//p' "$VERSION_FILE")
fi
case $SOURCE_DATE_EPOCH in
    ''|*[!0-9]*) fail "SOURCE_DATE_EPOCH must be a non-negative integer" ;;
esac
FORCE_SOURCE_DATE=1
export SOURCE_DATE_EPOCH FORCE_SOURCE_DATE

LOG_DIR=$PROJECT_DIR/build-logs/pgfplots-autonode
EXAMPLE_LOG_DIR=$PROJECT_DIR/examples/logs
mkdir -p "$LOG_DIR" "$EXAMPLE_LOG_DIR" \
    || fail "could not create autonode log directories"
CACHE_DIR=$LOG_DIR/cache
mkdir -p "$CACHE_DIR" || fail "could not create the LuaTeX cache directory"
TEXMFCACHE=$CACHE_DIR
TEXINPUTS=$PROJECT_DIR:${TEXINPUTS-}:
export TEXINPUTS TEXMFCACHE

normalize_log()
{
    log_file=$1
    awk '{ sub(/[[:space:]]+$/, ""); print }' "$log_file" \
        >"$log_file.normalized"
    mv -f "$log_file.normalized" "$log_file"
}

check_log()
{
    log_file=$1
    source_file=$2
    allow_rerun=${3:-false}
    diagnostics=$(awk -v allow_rerun="$allow_rerun" '
      allow_rerun == "true" &&
      (/^Package rerunfilecheck Warning:/ ||
       /^LaTeX Warning: Label\(s\) may have changed/ ||
       /^LaTeX Warning: There were undefined references\./) { next }
      /^(LaTeX( [^:]*)?|Package .*|Class .*) Warning:/ ||
      /^(pdfTeX|LuaTeX|LuaHBTeX) warning/ ||
      /^pgfplots-autonode warning:/ || /^(Over|Under)full \\[hv]box/ {
        if (++count <= 10) print NR ":" $0
      }
    ' "$log_file")
    [ -z "$diagnostics" ] || {
        printf 'error: diagnostics in %s (log: %s)\n%s\n' \
            "$source_file" "$log_file" "$diagnostics" >&2
        return 1
    }
    if grep -Ei 'luacoolprop\.(sty|tex|lua)' "$log_file" >/dev/null 2>&1; then
        fail "autonode build resolved LuaCoolProp while compiling $source_file"
    fi
}

run_latex()
{
    source_file=$1
    output_dir=$2
    log_file=$3
    if lualatex --interaction=nonstopmode --halt-on-error --file-line-error \
        --output-directory="$output_dir" "$PROJECT_DIR/$source_file" \
        >"$log_file" 2>&1; then :; else
        tail -n 20 "$log_file" >&2
        fail "LuaLaTeX failed for $source_file"
    fi
}

"$SCRIPT_DIR/check-autonode-documentation.sh"

for example_name in autonode-latex-basic autonode-affine-grid; do
    run_latex "examples/$example_name.tex" "$EXAMPLE_LOG_DIR" \
        "$EXAMPLE_LOG_DIR/$example_name.log"
    normalize_log "$EXAMPLE_LOG_DIR/$example_name.log"
    check_log "$EXAMPLE_LOG_DIR/$example_name.log" \
        "examples/$example_name.tex"
    mv -f "$EXAMPLE_LOG_DIR/$example_name.pdf" \
        "$PROJECT_DIR/examples/$example_name.pdf"
    rm -f "$EXAMPLE_LOG_DIR/$example_name.aux" \
        "$EXAMPLE_LOG_DIR/$example_name-error.log"
done

plain_log=$EXAMPLE_LOG_DIR/plain-autonode-basic.log
if luatex --interaction=nonstopmode --halt-on-error --file-line-error \
    --output-directory="$EXAMPLE_LOG_DIR" \
    "$PROJECT_DIR/examples/plain-autonode-basic.tex" >"$plain_log" 2>&1; then
    :
else
    tail -n 20 "$plain_log" >&2
    fail "plain LuaTeX autonode example failed"
fi
normalize_log "$plain_log"
check_log "$plain_log" examples/plain-autonode-basic.tex
mv -f "$EXAMPLE_LOG_DIR/plain-autonode-basic.pdf" \
    "$PROJECT_DIR/examples/plain-autonode-basic.pdf"

context_log=$EXAMPLE_LOG_DIR/context-autonode-basic.log
rm -f "$EXAMPLE_LOG_DIR/context-autonode-basic.pdf" \
    "$PROJECT_DIR/examples/context-autonode-basic.pdf"
if (cd "$EXAMPLE_LOG_DIR" && unset TEXMFCACHE && \
    context --luatex --once --batchmode --path="$PROJECT_DIR" \
    --result=context-autonode-basic \
    "$PROJECT_DIR/examples/context-autonode-basic.tex") \
    >"$context_log" 2>&1; then :; else
    tail -n 20 "$context_log" >&2
    fail "ConTeXt autonode example failed"
fi
normalize_log "$context_log"
check_log "$context_log" examples/context-autonode-basic.tex
mv -f "$EXAMPLE_LOG_DIR/context-autonode-basic.pdf" \
    "$PROJECT_DIR/examples/context-autonode-basic.pdf"

rm -f "$LOG_DIR"/pgfplots-autonode-manual.* "$LOG_DIR"/commands.* \
    "$LOG_DIR"/keys.*
run_latex pgfplots-autonode-manual.tex "$LOG_DIR" \
    "$LOG_DIR/pgfplots-autonode-manual-pass1.log"
for index_name in commands keys; do
    (cd "$LOG_DIR" && makeindex -o "$index_name.ind" -t "$index_name.ilg" \
        "$index_name.idx" >/dev/null 2>&1) \
        || fail "makeindex failed for autonode $index_name index"
done
run_latex pgfplots-autonode-manual.tex "$LOG_DIR" \
    "$LOG_DIR/pgfplots-autonode-manual-pass2.log"
run_latex pgfplots-autonode-manual.tex "$LOG_DIR" \
    "$LOG_DIR/pgfplots-autonode-manual-pass3.log"
for pass in 1 2 3; do
    normalize_log "$LOG_DIR/pgfplots-autonode-manual-pass$pass.log"
done
check_log "$LOG_DIR/pgfplots-autonode-manual-pass1.log" \
    pgfplots-autonode-manual.tex true
check_log "$LOG_DIR/pgfplots-autonode-manual-pass2.log" \
    pgfplots-autonode-manual.tex true
check_log "$LOG_DIR/pgfplots-autonode-manual-pass3.log" \
    pgfplots-autonode-manual.tex
cp -f "$LOG_DIR/pgfplots-autonode-manual-pass3.log" \
    "$LOG_DIR/pgfplots-autonode-manual.log"
mv -f "$LOG_DIR/pgfplots-autonode-manual.pdf" \
    "$PROJECT_DIR/pgfplots-autonode-manual.pdf"
rm -f "$LOG_DIR"/pgfplots-autonode-manual.aux \
    "$LOG_DIR"/pgfplots-autonode-manual.listing \
    "$LOG_DIR"/pgfplots-autonode-manual.out \
    "$LOG_DIR"/pgfplots-autonode-manual.toc \
    "$LOG_DIR"/commands.idx "$LOG_DIR"/commands.ilg "$LOG_DIR"/commands.ind \
    "$LOG_DIR"/keys.idx "$LOG_DIR"/keys.ilg "$LOG_DIR"/keys.ind

printf 'Built standalone pgfplots-autonode examples and manual.\n'
