# Build PostgreSQL from commitfest cf/4351 with distance-limit patch
FROM debian:bookworm-slim AS builder

RUN apt-get update && apt-get install -y \
    build-essential \
    git \
    libreadline-dev \
    zlib1g-dev \
    bison \
    flex \
    pkg-config \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /build

# Clone PostgreSQL and fetch commitfest branch
RUN git clone --depth=1 https://github.com/postgres/postgres.git postgresql && \
    cd postgresql && \
    git remote add commitfest https://github.com/postgresql-cfbot/postgresql.git && \
    git fetch --depth=1 commitfest cf/4351 && \
    git checkout FETCH_HEAD

# Copy and apply patches
COPY distance-limit.diff /build/
COPY profiling-instrumentation.diff /build/
RUN cd postgresql && \
    git apply /build/distance-limit.diff && \
    git apply /build/profiling-instrumentation.diff

# Configure and build
RUN cd postgresql && \
    ./configure --prefix=/usr/local/pgsql \
                --without-icu \
                --with-system-tzdata=/usr/share/zoneinfo && \
    make -j$(nproc) && \
    make install

# Runtime image
FROM debian:bookworm-slim

RUN apt-get update && apt-get install -y \
    libreadline8 \
    python3 \
    python3-pip \
    && rm -rf /var/lib/apt/lists/*

# Install psycopg for the benchmark script
RUN pip3 install --break-system-packages psycopg

# Copy PostgreSQL from builder
COPY --from=builder /usr/local/pgsql /usr/local/pgsql

# Set up environment
ENV PATH="/usr/local/pgsql/bin:$PATH"
ENV PGDATA="/var/lib/postgresql/data"
ENV LD_LIBRARY_PATH="/usr/local/pgsql/lib"

# Create postgres user and directories
RUN useradd -m postgres && \
    mkdir -p /var/lib/postgresql/data && \
    chown -R postgres:postgres /var/lib/postgresql

# Copy benchmark script
COPY prefetch_benchmark.py /opt/

WORKDIR /opt

USER postgres

# Initialize database and configure for TCP connections
RUN initdb -D /var/lib/postgresql/data && \
    echo "listen_addresses = '*'" >> /var/lib/postgresql/data/postgresql.conf && \
    echo "host all all 0.0.0.0/0 trust" >> /var/lib/postgresql/data/pg_hba.conf

# Expose PostgreSQL port
EXPOSE 5432

# Default command starts PostgreSQL
CMD ["postgres", "-D", "/var/lib/postgresql/data"]
