#!/usr/bin/env bash
# adom-jlcpcb cron smoke runner.
#
# Purpose: every ~1 h, run the full smoke suite against the live backend
# (the one this container IS serving), and alert via Kel on state
# transitions — not on every run.
#
# Alerting policy (mirrors adom-mouser's quota alert):
#   - PASS → PASS : silent
#   - PASS → FAIL : ALERT ("jlcpcb backend smoke test failing")
#   - FAIL → FAIL : silent (already alerted; don't spam)
#   - FAIL → PASS : ALERT ("jlcpcb backend recovered")
#
# State persisted to /tmp/adom-jlcpcb-smoke-state. Resets on reboot
# (which is fine — first run after reboot assumes PASS-state and only
# alerts on transition).
#
# Install (on service-jlcpcb):
#   (crontab -l 2>/dev/null; echo '15 * * * * /home/adom/adom-jlcpcb/tests/cron-smoke.sh >> /tmp/adom-jlcpcb-smoke.log 2>&1') | crontab -

set -u
set -a; [ -f /etc/environment ] && . /etc/environment; set +a

REPO_DIR="${ADOM_JLCPCB_REPO:-$HOME/adom-jlcpcb}"
STATE_FILE="${ADOM_JLCPCB_SMOKE_STATE:-/tmp/adom-jlcpcb-smoke-state}"
BACKEND="${JLCPCB_API:-http://127.0.0.1:${JLCPCB_PORT:-8774}}"
WEBHOOK="${KEL_ALERT_WEBHOOK:-}"
HOSTNAME_SHORT="$(hostname -s 2>/dev/null || echo jlcpcb-host)"

prev_status="pass"
[ -f "$STATE_FILE" ] && prev_status="$(cat "$STATE_FILE" 2>/dev/null || echo pass)"

log_out="$(bash "$REPO_DIR/tests/smoke.sh" "$BACKEND" 2>&1)"
status=$?
printf '[%s] status=%s\n%s\n' "$(date -Iseconds)" "$status" "$log_out"

new_status="pass"
[ "$status" -ne 0 ] && new_status="fail"

post_kel() {
  local text="$1"
  [ -z "$WEBHOOK" ] && return 0
  local body
  body="$(jq -n --arg t "$text" '{text:$t}')"
  curl -s --max-time 3 -X POST -H 'content-type: application/json' \
    -d "$body" "$WEBHOOK" >/dev/null || true
}

if [ "$prev_status" = "pass" ] && [ "$new_status" = "fail" ]; then
  # Extract summary + first 3 failing cases for the alert body.
  summary="$(printf '%s' "$log_out" | tail -25 | grep -E '^(FAIL|OK|FAIL.*passed)' | head -4)"
  post_kel "⚠️ *adom-jlcpcb backend smoke FAILING on $HOSTNAME_SHORT.*
Backend: $BACKEND
$(printf '%s' "$summary")
Check /tmp/adom-jlcpcb-smoke.log for the full run. This alert fires once per incident; no spam."
elif [ "$prev_status" = "fail" ] && [ "$new_status" = "pass" ]; then
  post_kel "✅ *adom-jlcpcb backend smoke RECOVERED on $HOSTNAME_SHORT.*
Backend: $BACKEND
All cases passing again."
fi

echo "$new_status" > "$STATE_FILE"
exit "$status"