#!/usr/bin/env bash
# Hit a sampled set of site-ng pages and assert each returns a healthy
# status code (2xx or expected redirect). Surfaces 500s before they
# get committed + pushed.
#
# Usage:
#   bash site-ng/scripts/smoke.sh                  # dev (default)
#   bash site-ng/scripts/smoke.sh https://...      # any host
#
# Add new URLs to the PATHS array as features land. Each one should
# exercise a *distinct* code path — duplicating shapes wastes time.
# The current set covers:
#   base.html (every page renders it)
#   home + content pages (no DB filter)
#   browse with type / include / exclude filters (the rx= path)
#   /instock/<slug> family (the inert-filter path that broke 2026-05-30)
#   /build (uses build_chart, build_header, more_sheet partials)
#   /changelog, /faq, /about (content templates)
#   /my-builds (auth-gated — 302 is healthy)
#   /login (auth flow entrypoint)
#
# Anything 3xx is treated as healthy (auth redirects, canonicalization
# redirects). Anything 4xx or 5xx is a failure. The script exits 1 on
# any failure so it can plug into `&&` chains: "smoke && git commit -F …".

set -u
# Default target: this box's primary LAN IP (autodetected), port 8088 —
# so the script follows the box instead of a hardcoded address. Falls
# back to 127.0.0.1 if detection turns up nothing. Pass a URL to override.
_LOCAL_IP="$(hostname -I 2>/dev/null | awk '{print $1}')"
BASE="${1:-http://${_LOCAL_IP:-127.0.0.1}:8088}"

PATHS=(
  '/'
  '/faq'
  '/changelog'
  '/browse?type=barrel'
  '/browse?type=barrel&r=Brownells'
  '/browse?type=barrel&rx=Bear%20Creek%20Arsenal'
  '/instock/new'
  '/instock/missed'
  '/instock/popular'
  '/instock/pricedrops'
  '/build'
  '/my-builds'
  '/login'
)

# Bright but optional. Skip color when piped (no tty).
if [ -t 1 ]; then
  G=$'\033[32m'; R=$'\033[31m'; D=$'\033[2m'; X=$'\033[0m'
else
  G=''; R=''; D=''; X=''
fi

echo "smoke @ $BASE"
fail=0
for p in "${PATHS[@]}"; do
  # --max-time so a hung dev server doesn't stall the whole sweep.
  code=$(curl -sS --max-time 10 -o /dev/null -w "%{http_code}" "$BASE$p" \
         2>/dev/null || echo "000")
  # 000 = curl couldn't connect (e.g. Flask dev-reload race after a
  # .py edit). One retry with a small delay catches that case without
  # masking a genuinely-down server (the retry will also 000 then).
  if [ "$code" = "000" ]; then
    sleep 1
    code=$(curl -sS --max-time 10 -o /dev/null -w "%{http_code}" "$BASE$p" \
           2>/dev/null || echo "000")
  fi
  if [[ "$code" =~ ^[23] ]]; then
    printf "  ${G}%s${X}  ${D}%s${X}\n" "$code" "$p"
  else
    printf "  ${R}%s${X}  %s\n" "$code" "$p"
    fail=1
  fi
done

if [ $fail -eq 0 ]; then
  printf "${G}OK${X} — all sampled pages healthy\n"
  exit 0
else
  printf "${R}FAIL${X} — at least one page broken; do not commit until fixed\n"
  exit 1
fi
