# Shared arqera-peer container base.
#
# Every per-platform manifest under ../../<platform>/ inherits from this.
# Builds a static MUSL binary on top of distroless (no shell, no
# package manager, ~5 MB final image). The peer-seed comes in via env
# var PEER_SEED at startup; each platform's secret manager injects it.
#
# Pattern per arq://doc/protocol/every-platform-is-a-peer-v1: every paid
# AND every free compute slot runs Rust. Marginal cost of an additional
# peer ≈ $0 because Rust's footprint (≈10 MB RSS idle) fits in every
# free tier on the planet.
#
# Build:
#   docker buildx build --platform linux/amd64,linux/arm64 \
#     --build-arg TWIN_VERSION=v0.3.0 \
#     -t ghcr.io/Arqera-IO/arqera-peer:v0.3.0 .

ARG TWIN_VERSION=v0.3.0

# ─── Stage 1 — download binaries from GitHub Release ──────────────────
FROM alpine:3.20 AS fetcher
ARG TWIN_VERSION
ARG TARGETARCH

RUN apk add --no-cache curl ca-certificates

# Map Docker TARGETARCH to GitHub-release artifact suffix
RUN case "$TARGETARCH" in \
    amd64) ARCH="x86_64-unknown-linux-musl" ;; \
    arm64) ARCH="aarch64-unknown-linux-musl" ;; \
    *) echo "unsupported arch: $TARGETARCH" >&2; exit 1 ;; \
    esac && \
    echo "$ARCH" > /tmp/arch && \
    BASE="https://github.com/Arqera-IO/ara-protocol/releases/download/${TWIN_VERSION}" && \
    curl -fsSL "${BASE}/twin-${ARCH}.tar.xz" -o /tmp/twin.tar.xz && \
    curl -fsSL "${BASE}/twin-fs-watcher-${ARCH}.tar.xz" -o /tmp/fs.tar.xz && \
    mkdir -p /out && \
    tar -xJf /tmp/twin.tar.xz -C /out --strip-components=1 && \
    tar -xJf /tmp/fs.tar.xz   -C /out --strip-components=1 && \
    chmod +x /out/twin /out/twin-fs-watcher

# ─── Stage 2 — minimal runtime (distroless) ──────────────────────────
FROM gcr.io/distroless/static-debian12:nonroot AS runtime

COPY --from=fetcher /out/twin            /usr/local/bin/twin
COPY --from=fetcher /out/twin-fs-watcher /usr/local/bin/twin-fs-watcher
COPY start.sh                            /usr/local/bin/start.sh

USER nonroot
WORKDIR /home/nonroot

# Required at runtime — each platform's secret manager must inject:
ENV PEER_SEED=""
ENV ARQERA_PEER_NAME=""
# Optional — capability tags that get appended at register time:
ENV ARQERA_PEER_TAGS=""
# Optional — over-ride defaults if the platform restricts watch surfaces:
ENV ARQERA_FS_WATCH_ROOTS="/home/nonroot/.arqera"

ENTRYPOINT ["/usr/local/bin/start.sh"]
