#!/command/with-contenv sh
set -eu

cd /app

python - <<'PY'
import os
import sys
import time

url = os.environ.get("DATABASE_URL", "")
if not url.startswith(("postgres://", "postgresql://")):
    print("DATABASE_URL must be a PostgreSQL URL", flush=True)
    sys.exit(1)

deadline = time.monotonic() + int(os.environ.get("POSTGRES_WAIT_SECONDS", "30"))

while True:
    try:
        import psycopg

        with psycopg.connect(url, connect_timeout=2) as connection:
            connection.execute("SELECT 1")
        print("PostgreSQL is available", flush=True)
        sys.exit(0)
    except Exception as exc:
        if time.monotonic() >= deadline:
            print(f"PostgreSQL is not available: {exc}", flush=True)
            sys.exit(1)
        time.sleep(1)
PY

echo "Running Django migrations"
exec s6-setuidgid django python manage.py migrate --noinput
