#!/usr/bin/env bash
# http-probe/apply — poll an HTTP endpoint until it returns the expected status (readiness gate for recipes).
# Run by role-helper as root; params JSON on stdin; outputs -> $SSR_OUTPUTS (no secrets).
#
# params: {"url":"http://10.13.13.20:5100/health","expectStatus":200,"tries":30,"intervalSeconds":5}
#     or  {"container":"apt-web","path":"/dists/bookworm/Release","expectStatus":200,…}
#         (container form: docker exec <container> wget -q -S -O /dev/null http://127.0.0.1<path>)
# outputs: status, attempts.  A mismatch after `tries` exits 1 with "expected <n>, got <m>".
set -euo pipefail
P=$(cat)
die() { echo "ERROR: $*" >&2; exit 1; }
URL=$(jq -r '.url // empty' <<<"$P")
CONT=$(jq -r '.container // empty' <<<"$P")
PATH_=$(jq -r '.path // "/"' <<<"$P")
EXPECT=$(jq -r '.expectStatus // 200' <<<"$P")
TRIES=$(jq -r '.tries // 30' <<<"$P")
INTERVAL=$(jq -r '.intervalSeconds // 5' <<<"$P")

[[ "$EXPECT" =~ ^[1-5][0-9][0-9]$ ]] || die "expectStatus must be 100-599"
[[ "$TRIES" =~ ^[0-9]{1,3}$ ]] && [ "$((10#$TRIES))" -ge 1 ] && [ "$((10#$TRIES))" -le 300 ] || die "tries must be 1-300"
[[ "$INTERVAL" =~ ^[0-9]{1,3}$ ]] && [ "$((10#$INTERVAL))" -le 300 ] || die "intervalSeconds must be 0-300"
TRIES=$((10#$TRIES)); INTERVAL=$((10#$INTERVAL))
[ $((TRIES * INTERVAL)) -le 3600 ] || die "tries * intervalSeconds must be at most 3600 seconds (got $((TRIES * INTERVAL)))"
if [ -n "$URL" ]; then
  [[ "$URL" =~ ^https?://[^[:space:]]+$ ]] || die "url must match ^https?://"
elif [ -n "$CONT" ]; then
  [[ "$CONT" =~ ^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$ ]] || die "invalid container name"
  [[ "$PATH_" =~ ^/[A-Za-z0-9._~/%?=\&:@+,-]*$ ]] || die "path must start with / and contain only URL-safe characters"
else
  die "url or container is required"
fi

probe() {
  if [ -n "$URL" ]; then
    curl -s --max-time 5 -o /dev/null -w '%{http_code}' "$URL" 2>/dev/null || true
  else
    docker exec "$CONT" wget -q -S -O /dev/null "http://127.0.0.1$PATH_" 2>&1 | sed -n 's/^ *HTTP\/[0-9.]* \([0-9][0-9][0-9]\).*/\1/p' | tail -n 1 || true
  fi
}

got=""; attempts=0
for i in $(seq 1 "$TRIES"); do
  attempts=$i
  got=$(probe)
  if [ "$got" = "$EXPECT" ]; then break; fi
  if [ "$i" -lt "$TRIES" ]; then sleep "$INTERVAL"; fi
done
[ "$got" = "$EXPECT" ] || die "expected $EXPECT, got ${got:-none} after $attempts attempts"
jq -n --argjson s "$((10#$got))" --argjson a "$attempts" '{status:$s,attempts:$a}' > "$SSR_OUTPUTS"
echo "probe ok: $got after $attempts attempt(s)"
