# syntax=docker/dockerfile:1.6
# Build arguments
ARG ELIXIR_VERSION=1.20.0
ARG OTP_VERSION=29.0.1
ARG DEBIAN_VERSION=trixie-20260518-slim

ARG BUILDER_IMAGE="hexpm/elixir:${ELIXIR_VERSION}-erlang-${OTP_VERSION}-debian-${DEBIAN_VERSION}"
ARG RUNNER_IMAGE="debian:${DEBIAN_VERSION}"

# Build stage
FROM ${BUILDER_IMAGE} AS builder

# Install build dependencies
RUN apt-get update -y && \
    apt-get install -y --no-install-recommends gcc g++ make git && \
    apt-get clean && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Install hex + rebar
RUN mix local.hex --force && \
    mix local.rebar --force

ENV MIX_ENV=prod

# Install mix dependencies
COPY mix.exs mix.lock ./
RUN mix deps.get --only $MIX_ENV && \
    mix deps.compile

# Copy config and application code, then compile
COPY config config
COPY lib lib
RUN mix compile

# Copy assets and static files, then deploy assets
COPY assets assets
COPY priv priv
RUN mix assets.deploy

# Copy release config and build release
COPY rel rel
RUN mix release

# Runtime stage
FROM ${RUNNER_IMAGE}

# Build timestamp baked in by CI (--build-arg BUILD_TIMESTAMP=...).
# Only consumed in this final stage, so it never busts the earlier
# compile cache.
ARG BUILD_TIMESTAMP=unknown

ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update -y && \
    apt-get install -y --no-install-recommends \
    libstdc++6 openssl libncurses6 locales ca-certificates libsctp1 && \
    sed -i '/en_US.UTF-8/s/^# //g' /etc/locale.gen && locale-gen && \
    apt-get clean && rm -rf /var/lib/apt/lists/* && \
    useradd -r -u 1001 -g root -s /bin/false elixir

ENV LANG=en_US.UTF-8 LANGUAGE=en_US:en LC_ALL=en_US.UTF-8

WORKDIR /app

# Ensure proper ownership
RUN chown -R elixir:root /app

COPY --from=builder --chown=elixir:root /app/_build/prod/rel/aprsme ./

RUN echo "${BUILD_TIMESTAMP}" > /app/BUILD_TIMESTAMP \
  && chown elixir:root /app/BUILD_TIMESTAMP

USER elixir
CMD ["/app/bin/server"]