#!/usr/bin/env bash
# Creates and starts an isolated PostgreSQL 18 dev cluster for Bousla on port 5433.
# Does NOT touch the machine's main PostgreSQL instance (port 5432).
# Usage: bash scripts/pg-dev-init.sh [app_password]
set -euo pipefail

PGBIN="/c/Program Files/PostgreSQL/18/bin"
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
DATA_DIR="$ROOT/.pgdata"
LOGS_DIR="$ROOT/pglogs"
PORT=5433

if [ -f "$DATA_DIR/PG_VERSION" ]; then
  echo "Dev cluster already exists at $DATA_DIR (nothing to do)."
  echo "To start it: bash scripts/pg-dev-start.sh"
  exit 0
fi

if [ $# -ge 1 ]; then
  APP_PASSWORD="$1"
else
  APP_PASSWORD="$(openssl rand -hex 16)"
fi
SUPERUSER_PASSWORD="$(openssl rand -hex 16)"

echo "==> Initializing cluster at $DATA_DIR (port $PORT)..."
mkdir -p "$LOGS_DIR"
# Windows has no unix sockets, so 'local' trust lines never apply; we bootstrap with
# host trust on 127.0.0.1, provision users, then harden to scram-sha-256 at the end.
"$PGBIN/initdb.exe" -D "$DATA_DIR" -U postgres -E UTF8 --locale=C \
  --auth-local=trust --auth-host=trust > "$LOGS_DIR/initdb.log" 2>&1
sed -i "s|^host    all             all             127.0.0.1/32            trust|host    all             all             127.0.0.1/32            scram-sha-256|" "$DATA_DIR/pg_hba.conf"

echo "==> Starting server on port $PORT (temporary trust window)..."
cp "$DATA_DIR/pg_hba.conf" "$DATA_DIR/pg_hba.conf.final"
sed -i "s|^host    all             all             127.0.0.1/32            scram-sha-256|host    all             all             127.0.0.1/32            trust|" "$DATA_DIR/pg_hba.conf"
"$PGBIN/pg_ctl.exe" -D "$DATA_DIR" -l "$LOGS_DIR/postgresql.log" \
  -o "-p $PORT -c listen_addresses=127.0.0.1" start

export PGHOST=127.0.0.1 PGPORT=$PORT PGUSER=postgres PGDATABASE=postgres

echo "==> Provisioning superuser password, application user and databases..."
"$PGBIN/psql.exe" -v ON_ERROR_STOP=1 <<SQL
ALTER USER postgres WITH PASSWORD '$SUPERUSER_PASSWORD';
CREATE USER bousla_app WITH PASSWORD '$APP_PASSWORD';
SQL
"$PGBIN/psql.exe" -v ON_ERROR_STOP=1 -c "CREATE DATABASE bousla_ops OWNER bousla_app ENCODING 'UTF8';"
"$PGBIN/psql.exe" -v ON_ERROR_STOP=1 -c "CREATE DATABASE bousla_ops_test OWNER bousla_app ENCODING 'UTF8';"

echo "==> Hardening: switching host auth to scram-sha-256..."
cp "$DATA_DIR/pg_hba.conf.final" "$DATA_DIR/pg_hba.conf"
rm -f "$DATA_DIR/pg_hba.conf.final"
"$PGBIN/pg_ctl.exe" -D "$DATA_DIR" reload

echo "$SUPERUSER_PASSWORD" > "$DATA_DIR/superuser_password.txt"
chmod 600 "$DATA_DIR/superuser_password.txt"

echo "==> Done. Application credentials (put these in apps/api/.env):"
echo "    PGHOST=127.0.0.1"
echo "    PGPORT=$PORT"
echo "    PGDATABASE=bousla_ops"
echo "    PGUSER=bousla_app"
echo "    PGPASSWORD=$APP_PASSWORD"
echo "    (superuser password stored in .pgdata/superuser_password.txt — gitignored)"
