ARG BASE_IMAGE=debian:trixie
FROM ${BASE_IMAGE}
ARG DEBIAN_FRONTEND=noninteractive

ARG POSTGRES_VERSION=16
ARG DOCUMENTDB_VERSION

RUN test -n "$DOCUMENTDB_VERSION" || (echo "DOCUMENTDB_VERSION not set" && false)

RUN apt-get update

RUN apt-get install -y --no-install-recommends \
    wget \
    gnupg2 \
    lsb-release \
    ca-certificates \
    locales \
    python3

RUN echo "en_US.UTF-8 UTF-8" > /etc/locale.gen && \
    locale-gen en_US.UTF-8

ENV LC_ALL=en_US.UTF-8
ENV LANGUAGE=en_US
ENV LC_COLLATE=en_US.UTF-8
ENV LC_CTYPE=en_US.UTF-8
ENV LANG=en_US.UTF-8

RUN echo "deb [signed-by=/usr/share/keyrings/pgdg-archive-keyring.gpg] http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main ${POSTGRES_VERSION}" > /etc/apt/sources.list.d/pgdg.list && \
    wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | gpg --dearmor > /usr/share/keyrings/pgdg-archive-keyring.gpg

RUN apt-get update && apt-get install -y --no-install-recommends \
    curl \
    tzdata \
    build-essential \
    pkg-config \
    cmake \
    git \
    postgresql-${POSTGRES_VERSION} \
    postgresql-server-dev-${POSTGRES_VERSION} \
    libpq-dev \
    libicu-dev \
    libkrb5-dev \
    postgresql-${POSTGRES_VERSION}-cron \
    postgresql-${POSTGRES_VERSION}-pgvector \
    postgresql-${POSTGRES_VERSION}-postgis-3 \
    postgresql-${POSTGRES_VERSION}-rum \
    devscripts \
    debhelper \
    dpkg-dev \
    && rm -rf /var/lib/apt/lists/*

COPY scripts /tmp/install_setup

RUN export CLEAN_SETUP=1 && \
    export INSTALL_DEPENDENCIES_ROOT=/tmp/install_setup && \
    MAKE_PROGRAM=cmake /tmp/install_setup/install_setup_libbson.sh && \
    /tmp/install_setup/install_setup_pcre2.sh && \
    /tmp/install_setup/install_setup_intel_decimal_math_lib.sh && \
    /tmp/install_setup/install_citus_indent.sh

# Set the working directory inside the container
WORKDIR /build

# Copy the source code into the container
COPY . /build

# Setup the debian packaging
COPY packaging/deb/common /build/debian
RUN sed -i "s/POSTGRES_VERSION/${POSTGRES_VERSION}/g" /build/debian/control
RUN sed -i "s/DOCUMENTDB_VERSION/${DOCUMENTDB_VERSION}/g" /build/debian/changelog

COPY packaging/deb/packaging-entrypoint.sh /usr/local/bin/packaging-entrypoint.sh

# Set the entrypoint
ENTRYPOINT ["packaging-entrypoint.sh"]
