#!/bin/sh

# Run every repository check from one reproducible entry point.  CoolProp stays
# outside this checkout: callers must provide its shared library explicitly.

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"
}

[ -n "${LUACOOLPROP_LIB:-}" ] \
    || fail "LUACOOLPROP_LIB must point to the CoolProp shared library"
case ${LUACOOLPROP_LIB##*/} in
    libCoolProp.dylib|libCoolProp.so|CoolProp.dll) ;;
    *) fail "LUACOOLPROP_LIB must name libCoolProp.dylib, libCoolProp.so, or CoolProp.dll" ;;
esac
[ -f "$LUACOOLPROP_LIB" ] \
    || fail "CoolProp library not found: $LUACOOLPROP_LIB"
[ -r "$LUACOOLPROP_LIB" ] \
    || fail "CoolProp library is not readable: $LUACOOLPROP_LIB"

need_command dirname
need_command awk
need_command lualatex
need_command mkdir
need_command sh
need_command tail
need_command texlua

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"
LIBRARY_DIR=$(CDPATH= cd -P "$(dirname "$LUACOOLPROP_LIB")" && pwd) \
    || fail "could not resolve LUACOOLPROP_LIB"
LIBRARY_NAME=${LUACOOLPROP_LIB##*/}
LUACOOLPROP_LIB=$LIBRARY_DIR/$LIBRARY_NAME
export LUACOOLPROP_LIB

# Test runners and sandboxes often make the user's TeX tree read-only.  Use a
# temporary cache by default, while preserving any explicit caller choice.
if [ -z "${LUACOOLPROP_TEX_CACHE:-}" ]; then
    LUACOOLPROP_TEX_CACHE=${TMPDIR:-/tmp}/luacoolprop-tex-cache
fi
export LUACOOLPROP_TEX_CACHE

LOG_DIR=$PROJECT_DIR/build-logs
mkdir -p "$LOG_DIR" || fail "could not create $LOG_DIR"

# The syntax pass is intentionally performed by /bin/sh: all project scripts
# must remain portable to the POSIX shell shipped by macOS.
for shell_script in "$SCRIPT_DIR"/*.sh; do
    [ -f "$shell_script" ] || fail "no scripts/*.sh files found"
    if ! sh -n "$shell_script"; then
        fail "shell syntax check failed: ${shell_script##*/}"
    fi
done
printf 'Shell syntax checks passed.\n'

"$SCRIPT_DIR/check-documentation.sh"

run_texlua_test()
{
    test_name=$1
    test_path=$2
    test_log=$LOG_DIR/$test_name.log

    printf 'Testing %s with texlua\n' "$test_path"
    if texlua "$PROJECT_DIR/$test_path" >"$test_log" 2>&1; then
        return 0
    fi

    printf 'error: texlua failed for %s (log: %s)\n' \
        "$test_path" "$test_log" >&2
    tail -n 20 "$test_log" >&2
    return 1
}

run_texlua_test test-luacoolprop tests/test-luacoolprop.lua

# This final step exercises LaTeX, plain TeX, and ConTeXt, regenerates all
# shipped examples and the indexed manual, and rejects TeX warnings.
"$SCRIPT_DIR/build-examples.sh"

printf 'All LuaCoolProp tests passed.\n'
