ARG ELIXIR_VERSION=1.18.3
ARG OTP_VERSION=27.3
ARG DEBIAN_VERSION=bookworm-20250224-slim
ARG BUILDER_IMAGE="hexpm/elixir:${ELIXIR_VERSION}-erlang-${OTP_VERSION}-debian-${DEBIAN_VERSION}"
ARG RUNNER_IMAGE="debian:${DEBIAN_VERSION}"

FROM ${BUILDER_IMAGE} AS builder
RUN apt-get update \
  && apt-get -y install \
    build-essential \
    git \
    make \
  && apt-get clean \
  && rm -rf /var/lib/ap/lists/*_*
WORKDIR /opt/app
# install hex + rebar
RUN mix do local.hex --force, local.rebar --force
# set build ENV
ARG BUILD_MIX_ENV=prod
ENV MIX_ENV=${BUILD_MIX_ENV}
# install mix dependencies
COPY mix.exs mix.lock ./
RUN mix deps.get --only ${MIX_ENV}
RUN mkdir config
# copy compile-time config files before we compile dependencies
# to ensure any relevant config change will trigger the dependencies
# to be re-compiled.
COPY config/config.exs config/${BUILD_MIX_ENV}.exs config/
RUN mix deps.compile
COPY priv priv
COPY lib lib
# Compile the release
RUN mix compile
# Changes to config/runtime.exs don't require recompiling the code
COPY config/runtime.exs config/
COPY rel rel
RUN mix release
COPY ./mix.exs ./
EXPOSE 4000
ENTRYPOINT ["./priv/docker/service/docker-entrypoint.sh"]
CMD ["sample-cookie"]

# start a new build stage so that the final image will only contain
# the compiled release and other runtime necessities
FROM ${RUNNER_IMAGE}
RUN apt-get update -y \
  && apt-get install -y \
    ca-certificates \
    libncurses5 \
    libstdc++6 \
    locales \
    openssl \
    tini \
  && apt-get clean && rm -f /var/lib/apt/lists/*_*
# Set the locale
RUN sed -i '/en_US.UTF-8/s/^# //g' /etc/locale.gen && locale-gen
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
WORKDIR /opt/app
RUN chown nobody /opt/app
# set runner ENV
ARG BUILD_MIX_ENV=prod
ENV MIX_ENV=${BUILD_MIX_ENV}
# Only copy the final release from the build stage
COPY --from=builder --chown=nobody:root /app/_build/${BUILD_MIX_ENV}/rel/wabanex ./
USER nobody
EXPOSE 4000
ENTRYPOINT ["tini", "--"]
CMD ["/app/bin/server"]
