#!/usr/bin/env bash
# Start Castopod stack with hard timeouts on pull/up (no infinite hang).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=lib.sh
source "${ROOT}/lib.sh"

cd "${CP_COMPOSE_DIR}"

echo "== pull (max ${CP_PULL_TIMEOUT}s) =="
cp_timeout "${CP_PULL_TIMEOUT}" podman-compose pull

echo "== up =="
cp_timeout 180 podman-compose up -d

echo "== wait for app on :9020 =="
# Castopod often 307 from /health to https — accept 2xx/3xx
ok=0
for ((i = 1; i <= CP_HEALTH_TRIES; i++)); do
  code=$(cp_http_code "http://127.0.0.1:9020/" || true)
  echo "try $i: local / → $code"
  if [[ "$code" =~ ^[23] ]]; then
    ok=1
    break
  fi
  sleep "${CP_HEALTH_SLEEP}"
done
[[ "$ok" -eq 1 ]] || { echo "ERROR: app not answering on 9020"; podman-compose ps; exit 1; }

echo "== public via Caddy =="
cp_wait_http "${CP_BASEURL}/" || true
echo "done."
