# syntax=docker/dockerfile:1
# Containerized build for voyem. Run on podman farm; each node produces
# a native Linux binary and, best-effort, a MinGW Windows binary for its
# architecture. The final stage is a runnable image published as
# quay.io/tangent/voyem. mkrel also extracts the binaries from it.
FROM rust:1-trixie AS builder

RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    clang \
    cmake \
    libclang-dev \
    mingw-w64 \
    ninja-build \
    pkg-config \
    python3 \
    xz-utils \
    zip \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /src

ARG VERSION=""
ARG OUTPUT_DIR=/artifacts

ENV VERSION=${VERSION}
ENV OUTPUT_DIR=${OUTPUT_DIR}

COPY Cargo.toml Cargo.lock build.rs ./
# `cargo fetch` rejects a manifest with no targets. The real sources
# replace these stubs in the next layer so dependency downloads stay cached.
RUN mkdir -p src \
    && printf 'fn main() {}\n' > src/main.rs \
    && : > src/lib.rs \
    && cargo fetch --locked

# Debian's mingw-w64 packages target Win32/Win64 x86 only. Windows/arm64
# needs the LLVM MinGW toolchain, which also covers Windows/amd64.
ARG TARGETARCH
RUN set -eu; \
    case "$TARGETARCH" in \
      amd64) mach=x86_64 ;; \
      arm64) mach=aarch64 ;; \
      *) echo "unsupported TARGETARCH=$TARGETARCH" >&2; exit 1 ;; \
    esac; \
    ver=20260224; \
    name="llvm-mingw-${ver}-ucrt-ubuntu-22.04-${mach}"; \
    url="https://github.com/mstorsjo/llvm-mingw/releases/download/${ver}/${name}.tar.xz"; \
    python3 -c 'import sys, urllib.request; urllib.request.urlretrieve(sys.argv[1], sys.argv[2])' \
        "$url" /tmp/llvm-mingw.tar.xz; \
    tar -C /opt -xJf /tmp/llvm-mingw.tar.xz; \
    ln -s "/opt/${name}" /opt/llvm-mingw; \
    rm /tmp/llvm-mingw.tar.xz
ENV PATH="/opt/llvm-mingw/bin:${PATH}"

COPY src ./src
COPY tools/container-build ./tools/container-build
RUN chmod +x tools/container-build && ./tools/container-build

# glibc, matching the dynamically linked Linux binary. voyem.exe is
# present only so mkrel can extract the Windows build.
FROM gcr.io/distroless/base-debian13
COPY --from=builder /artifacts/bin/ /
ENTRYPOINT ["/voyem"]
