# Shared helpers for the capstone scripts. Sourced, never run directly.
# Every capstone works in ~/labs/capstones/<name>, uses names starting with "cap-", and its
# reset.sh removes exactly what its setup.sh created.
set -euo pipefail

CAP_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APP_SRC="$CAP_ROOT/app"
FAILS=0

say()  { printf '\n== %s\n' "$*"; }
ok()   { printf '  PASS  %s\n' "$*"; }
bad()  { printf '  FAIL  %s\n' "$*"; FAILS=$((FAILS + 1)); }
need() { local t; for t in "$@"; do command -v "$t" >/dev/null || { echo "missing tool: $t (see the capstone page, Before you start)" >&2; exit 2; }; done; }
work() { WORK="$HOME/labs/capstones/$1"; mkdir -p "$WORK"; }

# check "description" command...: PASS if the command succeeds
check() { local d="$1"; shift; if "$@" >/dev/null 2>&1; then ok "$d"; else bad "$d"; fi; }

# wait_for URL [seconds]: until the URL answers with a 2xx
wait_for() {
  local url="$1" n="${2:-30}"
  for _ in $(seq "$n"); do curl -fsS -o /dev/null "$url" 2>/dev/null && return 0; sleep 1; done
  return 1
}

# port_free PORT: refuse to start if something already listens there
port_free() {
  if (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null; then
    echo "port $1 is in use; stop what uses it, or set a different port as the capstone page explains" >&2
    exit 3
  fi
}

summary() {
  if [ "$FAILS" -eq 0 ]; then printf '\nRESULT: all checks passed\n'; else printf '\nRESULT: %s check(s) failed\n' "$FAILS"; exit 1; fi
}
