# RSR-Certified Compliance Engine Container
# Supports Podman and Docker

# Build stage
FROM docker.io/rust:1.75-alpine AS builder

# Install build dependencies
RUN apk add --no-cache \
    musl-dev \
    openssl-dev \
    openssl-libs-static \
    pkgconfig \
    git

WORKDIR /build

# Copy manifests first for layer caching
COPY Cargo.toml Cargo.lock ./
COPY engine/Cargo.toml engine/
COPY lsp/Cargo.toml lsp/

# Create dummy source files to build dependencies
RUN mkdir -p engine/src lsp/src && \
    echo "fn main() {}" > engine/src/main.rs && \
    echo "pub fn lib() {}" > engine/src/lib.rs && \
    echo "fn main() {}" > lsp/src/main.rs

# Build dependencies only
RUN cargo build --release --package rsr-engine && \
    rm -rf engine/src lsp/src

# Copy actual source code
COPY engine/src engine/src
COPY lsp/src lsp/src

# Touch source files to trigger rebuild
RUN touch engine/src/main.rs engine/src/lib.rs lsp/src/main.rs

# Build the actual binaries
RUN cargo build --release --package rsr-engine --package rsr-lsp

# Runtime stage - minimal Alpine image
FROM docker.io/alpine:3.19 AS runtime

# Install runtime dependencies
RUN apk add --no-cache \
    ca-certificates \
    git \
    tini

# Create non-root user
RUN addgroup -g 1000 rsr && \
    adduser -u 1000 -G rsr -s /bin/sh -D rsr

# Copy binaries from builder
COPY --from=builder /build/target/release/rsr /usr/local/bin/
COPY --from=builder /build/target/release/rsr-lsp /usr/local/bin/

# Copy badge assets
COPY badges /usr/share/rsr/badges

# Set ownership
RUN chown -R rsr:rsr /usr/share/rsr

# Switch to non-root user
USER rsr

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD wget --no-verbose --tries=1 --spider http://localhost:8080/health || exit 1

# Default environment
ENV RSR_LOG_LEVEL=info \
    RSR_PLATFORMS=github,gitlab,bitbucket

EXPOSE 8080

# Use tini as init system
ENTRYPOINT ["/sbin/tini", "--"]

# Default command - run the server
CMD ["rsr", "serve", "--host", "0.0.0.0", "--port", "8080"]
