# Bundles the radicle-node release (rad, radicle-node, git-remote-rad) together
# with radicle-httpd into one image. The `node` and `httpd` compose services
# both run from this image, differing only by command/entrypoint.
#
# Binaries are statically linked (musl) and downloaded + signature/checksum
# verified from files.radicle.dev.
#
# Build:
#   docker build \
#     --build-arg RADICLE_VERSION=1.9.1 \
#     --build-arg RADICLE_HTTPD_VERSION=0.26.0 \
#     -t git.coopcloud.tech/c4dt/radicle:1.9.1 build/node
FROM debian:bookworm-slim AS fetch

ARG RADICLE_VERSION=1.9.1
ARG RADICLE_HTTPD_VERSION=0.26.0
ARG TARGET=x86_64-unknown-linux-musl

# pipefail so a failed download/cut in a pipe fails the checksum verification.
SHELL ["/bin/bash", "-o", "pipefail", "-c"]

RUN apt-get update && apt-get install -y --no-install-recommends \
        curl ca-certificates xz-utils \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /dist
RUN set -eux; \
    # radicle-node bundle (rad, radicle-node, git-remote-rad)
    curl --proto '=https' --tlsv1.2 -fSL \
        "https://files.radicle.dev/releases/${RADICLE_VERSION}/radicle-${TARGET}.tar.xz" \
        -o node.tar.xz; \
    curl --proto '=https' --tlsv1.2 -fSL \
        "https://files.radicle.dev/releases/${RADICLE_VERSION}/radicle-${TARGET}.tar.xz.sha256" \
        -o node.tar.xz.sha256; \
    echo "$(cut -d' ' -f1 node.tar.xz.sha256)  node.tar.xz" | sha256sum -c -; \
    # radicle-httpd (released separately, own version scheme + versioned filename)
    curl --proto '=https' --tlsv1.2 -fSL \
        "https://files.radicle.dev/releases/radicle-httpd/${RADICLE_HTTPD_VERSION}/radicle-httpd-${RADICLE_HTTPD_VERSION}-${TARGET}.tar.xz" \
        -o httpd.tar.xz; \
    curl --proto '=https' --tlsv1.2 -fSL \
        "https://files.radicle.dev/releases/radicle-httpd/${RADICLE_HTTPD_VERSION}/radicle-httpd-${RADICLE_HTTPD_VERSION}-${TARGET}.tar.xz.sha256" \
        -o httpd.tar.xz.sha256; \
    echo "$(cut -d' ' -f1 httpd.tar.xz.sha256)  httpd.tar.xz" | sha256sum -c -; \
    mkdir -p /out/bin; \
    tar -xJf node.tar.xz  --strip-components=2 -C /out/bin  --wildcards '*/bin/*'; \
    tar -xJf httpd.tar.xz --strip-components=2 -C /out/bin  --wildcards '*/bin/*'; \
    chmod +x /out/bin/*

FROM debian:bookworm-slim

# git + openssh are required at runtime: radicle-node shells out to git for
# fetches and uses ssh-keygen for key operations; curl is used by healthchecks.
RUN apt-get update && apt-get install -y --no-install-recommends \
        git openssh-client ca-certificates curl \
    && rm -rf /var/lib/apt/lists/*

COPY --from=fetch /out/bin/ /usr/local/bin/

ENV RAD_HOME=/var/lib/radicle
VOLUME ["/var/lib/radicle"]

# p2p (node) and HTTP API (httpd)
EXPOSE 8776 8080

# Default command runs the node; the httpd service overrides it in compose.
CMD ["radicle-node", "--listen", "0.0.0.0:8776", "--force"]
