#!/bin/sh
# Runs the test suite before anything leaves this machine.
#
# This exists because CI cannot be relied on here. The suite sat unrun for the
# whole life of the upstream project — nothing invoked `node --test`, so every
# assertion in tests/ was decoration. We wired up a workflow, and on our own
# Gitea it produced zero runs, most likely because no runner is registered.
#
# A hook is not a substitute for CI: it only protects the machine it is installed
# on, and --no-verify skips it. But it is the one layer that works with no server
# support at all, and it turns "the tests exist" back into "the tests ran".
#
# Install:  git config core.hooksPath .githooks
# Skip once (say the push is docs-only and node is unavailable):
#           git push --no-verify

set -e

if ! command -v node >/dev/null 2>&1; then
    echo "pre-push: node not found, skipping tests." >&2
    echo "          Run them wherever you do have node before merging." >&2
    exit 0
fi

echo "pre-push: checking generated files are up to date…"
if ! node portable/lib/i18n/build-messages.mjs --check; then
    echo "" >&2
    echo "pre-push: generated files are stale." >&2
    echo "          Run: node portable/lib/i18n/build-messages.mjs" >&2
    exit 1
fi

echo "pre-push: running tests…"
# Bare `node --test` discovers **/*.test.mjs. `node --test tests/` does not work:
# Node treats the path as a module to load and dies with "Cannot find module".
# That form was in CLAUDE.md for the life of the project, which is a good part of
# why nobody ever got the suite to run.
if ! node --test > /tmp/uclaw-prepush.log 2>&1; then
    echo "" >&2
    tail -40 /tmp/uclaw-prepush.log >&2
    echo "" >&2
    echo "pre-push: tests failed, push aborted." >&2
    echo "          Full output: /tmp/uclaw-prepush.log" >&2
    echo "          To push anyway: git push --no-verify" >&2
    exit 1
fi

passed=$(grep -oE '^# pass [0-9]+' /tmp/uclaw-prepush.log | grep -oE '[0-9]+' || echo '?')
echo "pre-push: $passed tests passed."
