#!/bin/sh
set -eu

# Attend qu'un endpoint HTTP réponde 2xx/3xx, avec retry.
# Entrées via variables d'environnement :
#   HEALTH_URL     (requis) : URL complète à vérifier (ex: http://127.0.0.1:3050/health)
#   MAX_RETRIES    (optionnel, default=30)
#   INTERVAL_MS    (optionnel, default=2000)
#   EXPECT_STATUS  (optionnel, default=accepte 200..399)

HEALTH_URL="${HEALTH_URL:-}"
MAX_RETRIES="${MAX_RETRIES:-30}"
INTERVAL_MS="${INTERVAL_MS:-2000}"
EXPECT_STATUS="${EXPECT_STATUS:-}"

if [ -z "$HEALTH_URL" ]; then
  echo "[wait-release-health] HEALTH_URL est requis" >&2
  exit 2
fi

if ! command -v curl >/dev/null 2>&1; then
  echo "[wait-release-health] curl introuvable dans le PATH" >&2
  exit 3
fi

interval_sec=$(awk -v ms="$INTERVAL_MS" 'BEGIN{ printf "%.3f", ms/1000 }')

attempt=0
last_status="000"
while [ "$attempt" -lt "$MAX_RETRIES" ]; do
  attempt=$((attempt + 1))
  last_status=$(curl -sS -o /dev/null -L --max-time 5 -w '%{http_code}' "$HEALTH_URL" 2>/dev/null || echo "000")
  if [ -n "$EXPECT_STATUS" ]; then
    if [ "$last_status" = "$EXPECT_STATUS" ]; then
      echo "[wait-release-health] OK ($last_status) après $attempt tentative(s) sur $HEALTH_URL"
      exit 0
    fi
  else
    case "$last_status" in
      2??|3??)
        echo "[wait-release-health] OK ($last_status) après $attempt tentative(s) sur $HEALTH_URL"
        exit 0
        ;;
    esac
  fi

  if [ "$attempt" -lt "$MAX_RETRIES" ]; then
    printf "[wait-release-health] tentative %d/%d: status=%s, nouvelle tentative dans %sms\n" \
      "$attempt" "$MAX_RETRIES" "$last_status" "$INTERVAL_MS"
    sleep "$interval_sec" 2>/dev/null || sleep 2
  fi
done

echo "[wait-release-health] KO après $MAX_RETRIES tentatives (dernier status=$last_status) sur $HEALTH_URL" >&2
exit 1

