ARG BUILDER_IMAGE=ours-rp-base-rust-amd64:1-bookworm
ARG RUNTIME_IMAGE=ours-rp-base-debian-arm64:bookworm-slim

FROM --platform=$BUILDPLATFORM ${BUILDER_IMAGE} AS builder

WORKDIR /src

RUN apt-get update \
    && apt-get install -y --no-install-recommends \
      build-essential \
      ca-certificates \
      clang \
      cmake \
      g++-aarch64-linux-gnu \
      gcc-aarch64-linux-gnu \
      git \
      libclang-dev \
      libc6-dev-arm64-cross \
      make \
      perl \
      pkg-config \
      python3 \
    && rm -rf /var/lib/apt/lists/* \
    && rustup target add aarch64-unknown-linux-gnu

ENV CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc \
    CC_aarch64_unknown_linux_gnu=aarch64-linux-gnu-gcc \
    CXX_aarch64_unknown_linux_gnu=aarch64-linux-gnu-g++ \
    AR_aarch64_unknown_linux_gnu=aarch64-linux-gnu-ar \
    CARGO_BUILD_TARGET=aarch64-unknown-linux-gnu \
    PKG_CONFIG_ALLOW_CROSS=1

COPY . .

RUN --mount=type=cache,target=/usr/local/cargo/registry \
    --mount=type=cache,target=/usr/local/cargo/git \
    --mount=type=cache,target=/src/target \
    cargo build --release --target aarch64-unknown-linux-gnu \
      --bin rpki \
      --bin rpki_daemon \
      --bin db_stats \
      --bin rpki_artifact_metrics \
    && mkdir -p /build-out/bin \
    && cp \
      target/aarch64-unknown-linux-gnu/release/rpki \
      target/aarch64-unknown-linux-gnu/release/rpki_daemon \
      target/aarch64-unknown-linux-gnu/release/db_stats \
      target/aarch64-unknown-linux-gnu/release/rpki_artifact_metrics \
      /build-out/bin/

FROM --platform=$TARGETPLATFORM ${RUNTIME_IMAGE} AS runtime

LABEL org.opencontainers.image.title="ours-rp-runtime" \
      org.opencontainers.image.description="Ours RP runtime image for ARM64 Docker Compose deployment"

RUN apt-get update \
    && apt-get install -y --no-install-recommends \
      bash \
      ca-certificates \
      coreutils \
      curl \
      findutils \
      iputils-ping \
      jq \
      procps \
      python3 \
      rsync \
      time \
      tzdata \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /opt/ours-rp

COPY --from=builder /build-out/bin/ /opt/ours-rp/bin/
COPY scripts/soak/run_soak.sh /opt/ours-rp/run_soak.sh
COPY scripts/soak/portable-soak.env.example /opt/ours-rp/portable-soak.env.example
COPY tests/fixtures/tal/ /opt/ours-rp/fixtures/tal/
COPY tests/fixtures/ta/ /opt/ours-rp/fixtures/ta/
COPY fixtures/live_20260619/tal/ /opt/ours-rp/fixtures/live_20260619/tal/
COPY fixtures/live_20260619/ta/ /opt/ours-rp/fixtures/live_20260619/ta/

RUN chmod +x /opt/ours-rp/run_soak.sh /opt/ours-rp/bin/* \
    && mkdir -p /var/lib/ours-rp/state /var/lib/ours-rp/runs /var/lib/ours-rp/logs /var/lib/ours-rp/tmp

ENV PACKAGE_ROOT=/opt/ours-rp \
    ENV_FILE=/opt/ours-rp/.env \
    RUN_ROOT=/var/lib/ours-rp \
    BIN_DIR=/opt/ours-rp/bin \
    FIXTURE_DIR=/opt/ours-rp/fixtures \
    RUST_BACKTRACE=1

VOLUME ["/var/lib/ours-rp"]

CMD ["/opt/ours-rp/run_soak.sh"]
