#!/usr/bin/env bash
set -Eeuo pipefail

log() { echo "[$(date -u +'%Y-%m-%dT%H:%M:%SZ')] $*"; }
fail() { echo "ERROR: $*" >&2; exit 1; }

: "${DB_HOST:?DB_HOST required}"
: "${DB_PORT:?DB_PORT required}"
: "${DB_NAME:?DB_NAME required}"

INTERVAL=${WAIT_FOR_DB_INTERVAL:-2}
TIMEOUT=${WAIT_FOR_DB_TIMEOUT:-30}

need() { command -v "$1" >/dev/null 2>&1 || fail "Required tool not found in PATH: $1"; }
need pg_isready

log "Waiting for database to be ready (timeout=${TIMEOUT}s, interval=${INTERVAL}s)"

end=$((SECONDS + TIMEOUT))
while (( SECONDS < end )); do
  if pg_isready -h "$DB_HOST" -p "$DB_PORT" -d "$DB_NAME" >/dev/null 2>&1; then
    log "Postgres is ready."
    exit 0
  fi
  sleep "$INTERVAL"
done

fail "Database not ready within ${TIMEOUT}s."