#!/usr/bin/env bash

set -euo pipefail

URL="${1:-http://localhost:3000/health/ready}"
COUNT="${COUNT:-12}"
SLEEP_SECONDS="${SLEEP_SECONDS:-5}"

ok_count=0
warn_count=0

for ((i=1; i<=COUNT; i++)); do
  code="$(curl -s -o /dev/null -w "%{http_code}" "$URL" || true)"
  printf '[%02d/%02d] %s -> %s\n' "$i" "$COUNT" "$URL" "$code"
  if [[ "$code" == "200" ]]; then
    ok_count=$((ok_count + 1))
  elif [[ "$code" == "502" || "$code" == "503" ]]; then
    warn_count=$((warn_count + 1))
  fi
  if [[ "$i" -lt "$COUNT" ]]; then
    sleep "$SLEEP_SECONDS"
  fi
done

printf '\nOK=%d WARN_502_503=%d TOTAL=%d\n' "$ok_count" "$warn_count" "$COUNT"

if [[ "$warn_count" -gt 0 ]]; then
  exit 1
fi
