#!/bin/sh
# =============================================================================
# PgBouncer entrypoint — render userlist from environment variables and start.
# =============================================================================
set -eu

USERLIST_TEMPLATE="/etc/pgbouncer/userlist.txt.template"
USERLIST="/etc/pgbouncer/userlist.txt"

if [ -z "${DB_USER:-}" ] || [ -z "${DB_PASSWORD:-}" ]; then
  echo "ERROR: DB_USER and DB_PASSWORD must be set" >&2
  exit 1
fi

# Render userlist from template, substituting env vars
envsubst < "$USERLIST_TEMPLATE" > "$USERLIST"
chmod 600 "$USERLIST"

echo "PgBouncer userlist rendered for user: ${DB_USER}"
echo "Starting PgBouncer on port 6432 (pool_mode=transaction, pool_size=${PGBOUNCER_POOL_SIZE:-20})..."

# Override pool settings via env vars if provided
if [ -n "${PGBOUNCER_POOL_SIZE:-}" ]; then
  sed -i "s/^default_pool_size = .*/default_pool_size = ${PGBOUNCER_POOL_SIZE}/" /etc/pgbouncer/pgbouncer.ini
fi

if [ -n "${PGBOUNCER_MAX_CLIENT_CONN:-}" ]; then
  sed -i "s/^max_client_conn = .*/max_client_conn = ${PGBOUNCER_MAX_CLIENT_CONN}/" /etc/pgbouncer/pgbouncer.ini
fi

exec pgbouncer /etc/pgbouncer/pgbouncer.ini
