# Define the base image dynamically
ARG BASE_IMAGE=ubuntu:22.04
FROM ${BASE_IMAGE}
ARG DEBIAN_FRONTEND=noninteractive

RUN apt-get update; \
    apt-get install -y --no-install-recommends software-properties-common jq curl sudo git make wget build-essential openssl pkg-config libssl-dev ca-certificates lsb-release gnupg2; \
    rm -rf /var/lib/apt/lists/*

RUN useradd -ms /bin/bash documentdb -G sudo
RUN mkdir -p /etc/sudoers.d && echo "%sudo ALL=(ALL:ALL) NOPASSWD: ALL" > /etc/sudoers.d/no-pass-ask

USER documentdb
WORKDIR /home/documentdb/code

COPY . /home/documentdb/code

RUN sudo chmod +x /home/documentdb/code/scripts/*.sh
RUN /home/documentdb/code/scripts/install_llvm.sh

# Install rustup (which includes rustc and cargo) in user directory
ENV RUSTUP_HOME=/home/documentdb/.rustup
ENV CARGO_HOME=/home/documentdb/.cargo
RUN mkdir -p $RUSTUP_HOME && mkdir -p $CARGO_HOME
ENV PATH=$PATH:$CARGO_HOME/bin

RUN /home/documentdb/code/scripts/install_rustup.sh --install-toolchain

RUN cargo install cargo-deb

RUN sudo chown -R documentdb:documentdb /home/documentdb/code

WORKDIR /home/documentdb/code/pg_documentdb_gw

RUN CARGO_MANIFEST_DIR=/home/documentdb/code/pg_documentdb_gw cargo build --profile=release-with-symbols

# Create /output directory and set permissions for the documentdb user
USER root
RUN mkdir -p /output && chown documentdb:documentdb /output
USER documentdb

CMD ["cargo", "deb", "--no-build", "--profile=release-with-symbols", "--output", "/output/"]