#!/bin/bash
set -e

echo "Starting Vault Agent to render PgBouncer config..."

# Start Vault Agent in background (runs as root for Vault capabilities)
vault agent -config=/vault/config/agent-config.hcl &
VAULT_PID=$!

# Wait for config to be rendered
echo "Waiting for PgBouncer config to be rendered..."
while [ ! -f /etc/pgbouncer/pgbouncer.ini ]; do
    sleep 1
done
echo "PgBouncer config rendered."

# Fix ownership of rendered config
chown pgbouncer:pgbouncer /etc/pgbouncer/pgbouncer.ini
chown -R pgbouncer:pgbouncer /var/run/pgbouncer

echo "Starting PgBouncer as pgbouncer user..."
# Run pgbouncer as non-root user
# Vault Agent (running as root) will send SIGHUP when credentials rotate
exec su-exec pgbouncer pgbouncer /etc/pgbouncer/pgbouncer.ini
