# PgBouncer with Vault Agent sidecar
# Vault Agent renders credentials, PgBouncer proxies connections

FROM alpine:3.20

# Install PgBouncer and dependencies
RUN apk add --no-cache \
    pgbouncer \
    curl \
    bash \
    postgresql-client \
    unzip \
    su-exec

# Create pgbouncer user and directories
# Remove default config - vault-agent will render our config
RUN adduser -D -H pgbouncer \
    && mkdir -p /var/run/pgbouncer /etc/pgbouncer /vault/templates /vault/secrets /vault/config /var/log/pgbouncer \
    && rm -f /etc/pgbouncer/pgbouncer.ini \
    && chown -R pgbouncer:pgbouncer /var/run/pgbouncer /etc/pgbouncer /var/log/pgbouncer

# Install Vault
ARG VAULT_VERSION=1.18.3
RUN curl -fsSL https://releases.hashicorp.com/vault/${VAULT_VERSION}/vault_${VAULT_VERSION}_linux_amd64.zip -o /tmp/vault.zip \
    && unzip /tmp/vault.zip -d /usr/local/bin \
    && rm /tmp/vault.zip \
    && chmod +x /usr/local/bin/vault

# Copy static userlist
COPY userlist.txt /etc/pgbouncer/userlist.txt
RUN chown pgbouncer:pgbouncer /etc/pgbouncer/userlist.txt

# Copy entrypoint
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh

EXPOSE 6432

ENTRYPOINT ["/entrypoint.sh"]
