# -------- Stage 1: Build --------
FROM debian:bookworm-slim AS builder

ARG BACKEND=softsign
ARG VERSION=main

# Install build dependencies
RUN apt-get update && \
    DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
    build-essential \
    clang \
    curl \
    git \
    pkg-config \
    libsodium-dev \
    libssl-dev \
    ca-certificates && \
    apt-get clean && rm -rf /var/lib/apt/lists/*

# Create non-root user
RUN useradd -m builder
USER builder
WORKDIR /home/builder

ENV PATH="/home/builder/.cargo/bin:$PATH"

# Install Rust
RUN curl https://sh.rustup.rs -sSf | sh -s -- -y && \
    rustup component add rustfmt clippy

# Clone and build TMKMS
RUN git clone --depth 1 --branch ${VERSION} https://github.com/iqlusioninc/tmkms.git && \
    cd tmkms && \
    cargo build --release --features=${BACKEND}

# -------- Stage 2: Runtime --------
FROM debian:bookworm-slim

# Install runtime dependencies only
RUN apt-get update && \
    DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
    libssl3 \
    libsodium23 \
    ca-certificates && \
    apt-get clean && rm -rf /var/lib/apt/lists/*

# Copy compiled binary
COPY --from=builder /home/builder/tmkms/target/release/tmkms /usr/local/bin/tmkms

# Set working directory
WORKDIR /

# Default command, override with `docker run ... bash` etc.
CMD ["tmkms"]
