#!/usr/bin/env bash
# Hourly cron entry point: run the API tests, email the report, keep a log.
#
# crontab -e:
#   0 * * * * /opt/race-api-automation/scripts/run-hourly.sh
#
# Exit code is the test result (0 = pass), so external monitors can use it too.
set -u

cd "$(dirname "$0")/.."
mkdir -p logs

# Make node/npx available under cron's minimal PATH (adjust if node lives elsewhere).
export PATH="/usr/local/bin:/usr/bin:/bin:${PATH:-}"

# Prevent overlapping runs if a previous one hangs.
exec 9>/tmp/race-api-automation.lock
if ! flock -n 9; then
  echo "$(date -u +%FT%TZ) previous run still active, skipping" >> logs/cron.log
  exit 0
fi

# Keep 30 days of logs.
find logs -name '*.log' -mtime +30 -delete 2>/dev/null

# Stale results must never be mistaken for this run's results.
rm -f test-results/results.json

{
  echo "=== $(date -u +%FT%TZ) run start ==="
  npx --no-install playwright test --project=api
  test_rc=$?
  node scripts/send-report.js
  report_rc=$?
  echo "=== run end: tests_rc=${test_rc} report_rc=${report_rc} ==="
  # Exit non-zero if tests failed OR the report could not be delivered.
  [ "$test_rc" -ne 0 ] && exit "$test_rc"
  exit "$report_rc"
} >> "logs/run-$(date -u +%F).log" 2>&1
