#!/bin/sh
set -e

PORT="${PORT:-${APP_PORT:-5000}}"

echo "Waiting for PostgreSQL at ${DATABASE_URL%%@*}@…"
python3 - <<'PY'
import os
import sys
import time

url = os.environ.get("DATABASE_URL", "").strip()
if not url:
    print("DATABASE_URL is not set", file=sys.stderr)
    sys.exit(1)

import psycopg

deadline = time.time() + 120
last_err = None
while time.time() < deadline:
    try:
        with psycopg.connect(url, connect_timeout=5):
            break
    except Exception as exc:
        last_err = exc
        time.sleep(2)
else:
    print(f"PostgreSQL not ready: {last_err}", file=sys.stderr)
    sys.exit(1)
PY

echo "Starting Amnezia Web Panel on 0.0.0.0:${PORT}"
exec uvicorn app:app \
  --host 0.0.0.0 \
  --port "${PORT}" \
  --proxy-headers \
  --forwarded-allow-ips='*'
