FROM rust:1.89-bookworm AS builder

WORKDIR /build

RUN set -eux; \
    cat > /etc/apt/sources.list.d/debian.sources <<'EOF'
Types: deb
URIs: http://mirrors.tuna.tsinghua.edu.cn/debian
Suites: bookworm bookworm-updates
Components: main
Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg

Types: deb
URIs: http://mirrors.tuna.tsinghua.edu.cn/debian-security
Suites: bookworm-security
Components: main
Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg
EOF

RUN apt-get update \
    && apt-get install -y --fix-missing --no-install-recommends \
        -o Acquire::Retries=10 \
        -o Acquire::http::Timeout=60 \
        build-essential \
        cmake \
        pkg-config \
        clang \
        libclang-dev \
        libssl-dev \
    && rm -rf /var/lib/apt/lists/*

COPY Cargo.toml Cargo.lock ./
COPY src ./src

RUN cargo build --release --bin rpki_rtr

FROM debian:bookworm-slim AS runtime

RUN set -eux; \
    cat > /etc/apt/sources.list.d/debian.sources <<'EOF'
Types: deb
URIs: http://mirrors.tuna.tsinghua.edu.cn/debian
Suites: bookworm bookworm-updates
Components: main
Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg

Types: deb
URIs: http://mirrors.tuna.tsinghua.edu.cn/debian-security
Suites: bookworm-security
Components: main
Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg
EOF

RUN apt-get update \
    && apt-get install -y --fix-missing --no-install-recommends \
        -o Acquire::Retries=10 \
        -o Acquire::http::Timeout=60 \
        ca-certificates \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

COPY --from=builder /build/target/release/rpki_rtr /usr/local/bin/rpki_rtr
COPY --chmod=755 deploy/server/entrypoint.sh /usr/local/bin/rpki-rtr-entrypoint.sh

RUN mkdir -p /app/data /app/rtr-db /app/certs /app/slurm /app/logs

ENV RPKI_RTR_ENABLE_TLS=false \
    RPKI_RTR_TCP_ADDR=0.0.0.0:323 \
    RPKI_RTR_TLS_ADDR=0.0.0.0:324 \
    RPKI_RTR_DB_PATH=/app/rtr-db \
    RPKI_RTR_CCR_DIR=/app/data \
    RPKI_RTR_SLURM_DIR=/app/slurm \
    RPKI_RTR_REFRESH_INTERVAL_SECS=300 \
    RPKI_RTR_STRICT_CCR_VALIDATION=false

EXPOSE 323 324

ENTRYPOINT ["/usr/local/bin/rpki-rtr-entrypoint.sh"]
