#!/bin/bash
# Runs once on first container start (docker-entrypoint-initdb.d).
# Sets Supabase internal role passwords to POSTGRES_PASSWORD and creates
# required schemas with correct grants.

set -e

PASS="${POSTGRES_PASSWORD:-postgres}"

psql -v ON_ERROR_STOP=1 --username supabase_admin --dbname postgres <<-EOSQL
    -- Set passwords for all Supabase internal roles.
    -- The supabase/postgres image creates them with hardcoded defaults;
    -- this overrides them so services connect with POSTGRES_PASSWORD.
    ALTER ROLE authenticator              WITH PASSWORD '${PASS}';
    ALTER ROLE supabase_auth_admin        WITH PASSWORD '${PASS}';
    ALTER ROLE supabase_replication_admin WITH PASSWORD '${PASS}';
    ALTER ROLE supabase_storage_admin     WITH PASSWORD '${PASS}';
    ALTER ROLE pgbouncer                  WITH PASSWORD '${PASS}';

    -- Create the _realtime schema required by supabase/realtime
    CREATE SCHEMA IF NOT EXISTS _realtime;
    GRANT ALL ON SCHEMA _realtime TO supabase_replication_admin;
    ALTER ROLE supabase_replication_admin SET search_path TO _realtime;

    -- Pre-create the `realtime` schema. Realtime's per-tenant migrations
    -- expect it to exist before running (they don't CREATE SCHEMA themselves)
    -- and without it every tenant connect fails with "schema realtime does
    -- not exist" → PoolingReplicationError → no postgres_changes delivery.
    CREATE SCHEMA IF NOT EXISTS realtime AUTHORIZATION supabase_admin;
EOSQL

echo "==> db-init: role passwords and schemas configured"
