# Example of how to build this container (ran from pgrx checkout directory):
#   docker build --build-arg PG_MAJOR_VER=14 -f .github/docker/Dockerfile.debian_bullseye -t pgrx-debian .
#
# Example of how to run this container with tests after building the image:
#   docker run pgrx-debian cargo test --no-default-features --features pg14 --locked
#
# Note that "PG_MAJOR_VER" build arg in the build step must match the
# "--features pgXX" in the run step

FROM debian:bullseye

ARG PG_MAJOR_VER
ENV PG_MAJOR_VER=${PG_MAJOR_VER}

ARG DEBIAN_FRONTEND=noninteractive

RUN apt-get update
RUN apt-get install -y wget gnupg
RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ bullseye-pgdg main" >> /etc/apt/sources.list.d/pgdg.list
RUN wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | apt-key add -
RUN apt-get update -y --fix-missing
RUN apt-get install -y \
  build-essential \
  curl \
  clang \
  git \
  gcc \
  libssl-dev \
  libz-dev \
  make \
  pkg-config \
  postgresql-$PG_MAJOR_VER \
  postgresql-server-dev-$PG_MAJOR_VER \
  zlib1g-dev \
  && rm -rf /var/lib/apt/lists/*

# Set up permissions so that the rust user below can create extensions
RUN chmod a+rwx `$(which pg_config) --pkglibdir` \
  `$(which pg_config) --sharedir`/extension \
  /var/run/postgresql/

# Running pgrx and tests require a non-root user
RUN useradd --create-home --shell /bin/bash rust
WORKDIR /checkout
RUN chown -R rust:rust /checkout
COPY --chown=rust:rust . /checkout

USER rust

# This environment variable is required for postgres while running the tests
ENV USER=rust

# Install cargo and Rust
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
ENV PATH="/home/rust/.cargo/bin:${PATH}"

# By default, we always want to use '--locked'. However, there are some circumstances
# where we might want to try it unlocked. In those one-off scenarios, the image
# can be built by docker with: --build-arg CARGO_LOCKED_OPTION=''
ARG CARGO_LOCKED_OPTION='--locked'
ENV CARGO_LOCKED_OPTION=${CARGO_LOCKED_OPTION}

# Install cargo-pgrx from source copied into this container
RUN echo "Running cargo install --path cargo-pgrx/ $CARGO_LOCKED_OPTION" && cargo install --path cargo-pgrx/ $CARGO_LOCKED_OPTION

# Initialize cargo pgrx so that we can run the tests
RUN cargo pgrx init --pg$PG_MAJOR_VER=$(which pg_config)

CMD ["cargo", "test", "--no-default-features", "--features", "pg${PG_MAJOR_VER} cshim", "${CARGO_LOCKED_OPTION}"]
