# Build pg_trickle from source for demo/testing
# Usage: docker build -t pg_trickle:demo -f Dockerfile.demo .

FROM rust:latest AS builder

# Install Rust nightly toolchain (required for cargo-pgrx v0.18 edition2024)
RUN rustup install nightly && rustup default nightly

# Install PostgreSQL 18 dev dependencies
# Add PostgreSQL official repository for PG 18 (using modern GPG key method)
# Use trixie-pgdg repo since rust:latest is based on Debian Trixie (13)
RUN apt-get update && apt-get install -y \
    curl \
    gnupg \
    && curl https://www.postgresql.org/media/keys/ACCC4CF8.asc | gpg --dearmor -o /etc/apt/trusted.gpg.d/postgresql.gpg \
    && echo "deb [signed-by=/etc/apt/trusted.gpg.d/postgresql.gpg] http://apt.postgresql.org/pub/repos/apt trixie-pgdg main" > /etc/apt/sources.list.d/pgdg.list \
    && apt-get update && apt-get install -y \
    postgresql-server-dev-18 \
    pkg-config \
    libssl-dev \
    clang \
    && rm -rf /var/lib/apt/lists/*

# Copy source and build
WORKDIR /build
COPY . /build

# Build extension (cargo-pgrx v0.18+ requires Rust nightly for edition2024)
# Initialize pgrx to use system PostgreSQL, then package the extension
RUN cargo install cargo-pgrx && \
    export PGRX_HOME=/pgrx && \
    export PG_CONFIG=/usr/lib/postgresql/18/bin/pg_config && \
    cargo pgrx init --pg18 /usr/lib/postgresql/18/bin/pg_config && \
    cargo pgrx package

# Final stage: PostgreSQL with built extension
FROM postgres:18.3-bookworm

# Install runtime dependencies
RUN apt-get update && apt-get install -y \
    libssl3 \
    && rm -rf /var/lib/apt/lists/*

# Copy built extension from builder
# cargo pgrx package outputs to target/release/pg_trickle-pg18/
COPY --from=builder /build/target/release/pg_trickle-pg18/usr/share/postgresql/18/extension/* /usr/share/postgresql/18/extension/
COPY --from=builder /build/target/release/pg_trickle-pg18/usr/lib/postgresql/18/lib/*.so /usr/lib/postgresql/18/lib/
