#!/bin/bash
# Add pg_hba entries for remote connections to an already-initialized DB.
# Run this once if you started the DB before adding etc/pg-init-remote.sh.
set -e
CONTAINER="${1:-momswap-backend-db}"
if ! docker ps --format '{{.Names}}' | grep -q "^${CONTAINER}$"; then
  echo "Container ${CONTAINER} is not running. Start it with: docker compose up -d db"
  exit 1
fi
docker exec "$CONTAINER" bash -c '
  PGDATA=/var/lib/postgresql/data
  if grep -q "0.0.0.0/0" "$PGDATA/pg_hba.conf" 2>/dev/null; then
    echo "Remote access already configured."
    exit 0
  fi
  echo "host all all 0.0.0.0/0 scram-sha-256" >> "$PGDATA/pg_hba.conf"
  echo "host all all ::/0 scram-sha-256" >> "$PGDATA/pg_hba.conf"
  psql -U "${POSTGRES_USER:-momswap}" -d "${POSTGRES_DB:-momswap}" -c "SELECT pg_reload_conf();"
  echo "Remote access configured. Reloaded PostgreSQL."
'
