#!/bin/sh
set -eu

SLOT="${1:-}"
if [ -z "$SLOT" ] || [ "$SLOT" = "--help" ] || [ "$SLOT" = "-h" ]; then
  echo "Usage:"
  echo "  $0 blue   # inspecte web_blue"
  echo "  $0 green  # inspecte web_green"
  exit 0
fi

case "$SLOT" in
  blue)  SERVICE="web_blue";  CNAME="archicratie-web-blue" ;;
  green) SERVICE="web_green"; CNAME="archicratie-web-green" ;;
  *) echo "Slot invalide: $SLOT (attendu: blue|green)"; exit 1 ;;
esac

ROOT="$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)"
cd "$ROOT"

echo "== .env (valeurs build) =="
if [ -f ".env" ]; then
  cat .env
else
  echo "(absent)"
fi
echo ""

# Récupère container id via compose si possible
CID="$(docker compose ps -q "$SERVICE" 2>/dev/null || true)"
if [ -n "$CID" ]; then
  TARGET="$CID"
else
  TARGET="$CNAME"
fi

echo "== Extraction dans le conteneur ($SLOT) =="
if ! docker inspect "$TARGET" >/dev/null 2>&1; then
  echo "Conteneur introuvable: $TARGET"
  echo "Astuce: docker compose up -d $SERVICE"
  exit 1
fi

# Cherche la ligne JS injectée dans le HTML (format vu chez toi : const GITEA_BASE = "...")
docker exec -it "$TARGET" sh -lc '
set -eu
F="$(grep -Ril "const GITEA_BASE" /usr/share/nginx/html 2>/dev/null | head -n 1 || true)"
if [ -z "$F" ]; then
  echo "ERREUR: impossible de trouver GITEA_BASE dans le HTML"
  exit 2
fi
echo "Fichier exemple: $F"
LINE="$(grep -Rin "const GITEA_BASE" "$F" | head -n 1)"
echo "$LINE"
echo ""
echo "Snippet (GITEA_BASE/OWNER/REPO) :"
grep -Rin "const GITEA_BASE\|const GITEA_OWNER\|const GITEA_REPO" "$F" | head -n 20
' || true

echo ""
echo "== Tests HTTP (depuis le NAS) =="
# Parse .env proprement (sans source/bashex)
BASE="$(grep -E '^PUBLIC_GITEA_BASE=' .env 2>/dev/null | sed 's/^PUBLIC_GITEA_BASE=//' | tr -d '\r' || true)"
OWNER="$(grep -E '^PUBLIC_GITEA_OWNER=' .env 2>/dev/null | sed 's/^PUBLIC_GITEA_OWNER=//' | tr -d '\r' || true)"
REPO="$(grep -E '^PUBLIC_GITEA_REPO=' .env 2>/dev/null | sed 's/^PUBLIC_GITEA_REPO=//' | tr -d '\r' || true)"

if [ -z "$BASE" ] || [ -z "$OWNER" ] || [ -z "$REPO" ]; then
  echo "WARN: .env incomplet (BASE/OWNER/REPO)."
  exit 0
fi

echo "Repo: $BASE/$OWNER/$REPO/"
curl -kI "$BASE/$OWNER/$REPO/" | head -n 12 || true
echo ""
echo "Issue new: $BASE/$OWNER/$REPO/issues/new"
curl -kI "$BASE/$OWNER/$REPO/issues/new" | head -n 15 || true
