# syntax=docker/dockerfile:1

# glibc (Debian) based image for AdGuardian-Term
# used for the targets where the scratch/musl build doesn't work:
# the 32-bit arches, plus the big-iron 64-bit ppc64le / s390x
#
# The binary needs to be CROSS-compiled on the native build platform and then
# packaged into a target-arch runtime image

# Build: cross-compile for the requested target
FROM --platform=$BUILDPLATFORM rust:1.90-slim-bookworm AS builder
ARG TARGETPLATFORM

# Base build tooling
RUN apt-get update \
    && apt-get install -y --no-install-recommends \
       build-essential cmake clang perl ca-certificates \
    && rm -rf /var/lib/apt/lists/*

# Install the cross C toolchain + matching Rust target for the target platform
RUN set -eux; \
    case "$TARGETPLATFORM" in \
      "linux/arm/v7")  rust_target=armv7-unknown-linux-gnueabihf; gnu=arm-linux-gnueabihf ;; \
      "linux/386")     rust_target=i686-unknown-linux-gnu;        gnu=i686-linux-gnu ;; \
      "linux/ppc64le") rust_target=powerpc64le-unknown-linux-gnu; gnu=powerpc64le-linux-gnu ;; \
      "linux/s390x")   rust_target=s390x-unknown-linux-gnu;       gnu=s390x-linux-gnu ;; \
      *) echo "Unsupported TARGETPLATFORM: $TARGETPLATFORM" >&2; exit 1 ;; \
    esac; \
    apt-get update; \
    apt-get install -y --no-install-recommends "gcc-${gnu}" "g++-${gnu}"; \
    rm -rf /var/lib/apt/lists/*; \
    rustup target add "$rust_target"; \
    triple_upper=$(echo "$rust_target" | tr 'a-z-' 'A-Z_'); \
    triple_under=$(echo "$rust_target" | tr '-' '_'); \
    { \
      echo "export RUST_TARGET=${rust_target}"; \
      echo "export CARGO_TARGET_${triple_upper}_LINKER=${gnu}-gcc"; \
      echo "export CC_${triple_under}=${gnu}-gcc"; \
      echo "export CXX_${triple_under}=${gnu}-g++"; \
      echo "export AR_${triple_under}=${gnu}-ar"; \
    } > /cross-env.sh

WORKDIR /app
COPY . .
RUN --mount=type=cache,target=/usr/local/cargo/registry,id=cargo-reg-full-${TARGETPLATFORM} \
    . /cross-env.sh \
    && cargo build --release --target "$RUST_TARGET" \
    && cp "target/${RUST_TARGET}/release/adguardian" /adguardian

# Runtime: minimal glibc base, CA certs copied from builder, run as non-root.
# No RUN here, so this stage needs no emulation despite being target-arch
FROM debian:bookworm-slim
LABEL org.opencontainers.image.title="AdGuardian-Term" \
      org.opencontainers.image.description="Real-time traffic monitoring for AdGuard Home, in your terminal" \
      org.opencontainers.image.source="https://github.com/Lissy93/AdGuardian-Term" \
      org.opencontainers.image.licenses="MIT"
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
ENV SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt
COPY --from=builder /adguardian /usr/local/bin/adguardian
USER 65534:65534
ENTRYPOINT ["/usr/local/bin/adguardian"]
