#!/usr/bin/env bash
# Cloud Bongos self-host container entrypoint (V4.R63, task 1202).
#   1. wait for Postgres to accept connections,
#   2. apply migrations (game module skipped automatically — it is off in a vanilla instance),
#   3. exec the GDS-only platform server.
# No prod topology: every connection detail comes from PG* env (docker-compose.yml).
set -euo pipefail

: "${PGHOST:?PGHOST must be set (the Postgres service host)}"
: "${PGDATABASE:?PGDATABASE must be set (the instance database name)}"
PGPORT="${PGPORT:-5432}"

echo "cloud-bongos: waiting for Postgres at ${PGHOST}:${PGPORT}/${PGDATABASE} ..."
for i in $(seq 1 60); do
  if pg_isready -h "$PGHOST" -p "$PGPORT" -d "$PGDATABASE" >/dev/null 2>&1; then
    echo "cloud-bongos: Postgres is ready."
    break
  fi
  if [ "$i" = "60" ]; then
    echo "cloud-bongos: Postgres did not become ready in time" >&2
    exit 1
  fi
  sleep 1
done

echo "cloud-bongos: applying migrations ..."
bash scripts/migrate.sh

echo "cloud-bongos: starting platform server (GDS-only) ..."
exec node src/platform-server.js
