#!/bin/sh
# Pre-commit hook: run the Battle for 'Tismo test suite and refuse the
# commit when anything fails, then refresh the generated devlog the main menu
# shows. Installed by scripts/install-git-hooks.sh, which points the repository
# at this directory via core.hooksPath.
#
# Skip it once with: git commit --no-verify

set -e

# Locate the project root from this hook's own path, so the hook works no
# matter which directory the commit was invoked from.
PROJECT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$PROJECT_DIR"

echo "pre-commit: running the test suite..."

if command -v node >/dev/null 2>&1; then
  node tests/run_tests.js
elif command -v nodejs >/dev/null 2>&1; then
  nodejs tests/run_tests.js
elif command -v nix-shell >/dev/null 2>&1; then
  # Node is not on PATH; use the pinned nixpkgs one like the dev environment.
  nix-shell -p nodejs --run "node tests/run_tests.js"
else
  echo "pre-commit: no Node.js runtime found (looked for node, nodejs, nix-shell)." >&2
  echo "pre-commit: install Node.js, or commit with --no-verify to skip the tests." >&2
  exit 1
fi

# Refresh the devlog the main menu shows and stage it, so the committed client
# always carries the latest commits. A failure here must not block the commit.
echo "pre-commit: refreshing the devlog..."
if command -v node >/dev/null 2>&1; then
  node scripts/generate-devlog.js
elif command -v nodejs >/dev/null 2>&1; then
  nodejs scripts/generate-devlog.js
else
  nix-shell -p nodejs --run "node scripts/generate-devlog.js"
fi || echo "pre-commit: skipped the devlog refresh." >&2
if [ -f client/js/devlog_data.js ]; then
  git add -- client/js/devlog_data.js
fi
