#!/usr/bin/env bash
# wait-for-url.sh — curl with retry until success or attempts exhausted.
#
# Usage: wait-for-url.sh <url> [<max-attempts>] [<delay-seconds>]
# Env (optional): BASIC_AUTH_USER, BASIC_AUTH_PASS — if set, sent as basic auth.
set -euo pipefail

URL="${1:-}"
MAX_ATTEMPTS="${2:-30}"
DELAY="${3:-2}"

if [ -z "$URL" ]; then
  echo "usage: $0 <url> [<max-attempts>] [<delay-seconds>]" >&2
  exit 2
fi

# bash 3.2-safe: expand array only when non-empty.
AUTH_ARGS=()
if [ -n "${BASIC_AUTH_USER:-}" ] && [ -n "${BASIC_AUTH_PASS:-}" ]; then
  AUTH_ARGS=(--user "${BASIC_AUTH_USER}:${BASIC_AUTH_PASS}")
fi

# The upstream WAF (flights.test.aeroflot.ru) blocks the default curl UA
# and serves an HTML "Доступ временно ограничен" page. Pretend to be a
# real browser so /api/* probes actually reach the API.
UA='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Safari/537.36'

attempt=1
while [ "$attempt" -le "$MAX_ATTEMPTS" ]; do
  if curl -fsS -A "$UA" ${AUTH_ARGS[@]+"${AUTH_ARGS[@]}"} -o /dev/null "$URL"; then
    echo "ok: $URL ($attempt attempt(s))"
    exit 0
  fi
  if [ "$attempt" -lt "$MAX_ATTEMPTS" ]; then
    sleep "$DELAY"
  fi
  attempt=$((attempt + 1))
done

echo "fail: $URL did not return 2xx after $MAX_ATTEMPTS attempts" >&2
echo "--- Diagnostic: Attempting to reach the URL one more time to capture the error ---" >&2
curl -sS -A "$UA" ${AUTH_ARGS[@]+"${AUTH_ARGS[@]}"} -w "\nHTTP_CODE=%{http_code}\nTIME=%{time_total}s\nSIZE=%{size_download}\n" -o /dev/null "$URL" || true
exit 1
