# Unified Dockerfile for docx-mcp
# Features:
# - HTTP mode (HTML interface) + stdio mode
# - LibreOffice for high-fidelity PDF conversion
# - Templates directory support
# - Sandboxed, non-root, read-only filesystem where possible

# ============================================================
# Build Stage
# ============================================================
FROM rust:1.90-slim AS builder

# Install build dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    pkg-config \
    libssl-dev \
    libfontconfig1-dev \
    libfreetype6-dev \
    libjpeg-dev \
    libpng-dev \
    build-essential \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Copy manifests and source
COPY Cargo.toml Cargo.lock build.rs ./
COPY src/ ./src/
COPY benches/ ./benches/
COPY assets/ ./assets/

# Build with all key features enabled:
# - runtime-server: stdio MCP transport
# - http-server: HTTP + HTML interface
# - advanced-docx: advanced document operations
# - build-bin: enables building the docx-mcp binary
RUN cargo build --release --features "runtime-server http-server advanced-docx build-bin"

# ============================================================
# Runtime Stage
# ============================================================
FROM debian:bookworm-slim AS runtime

# Install runtime dependencies (including LibreOffice for better PDF conversion)
RUN apt-get update && apt-get install -y --no-install-recommends \
    libssl3 \
    libfontconfig1 \
    libfreetype6 \
    libjpeg62-turbo \
    libpng16-16 \
    ca-certificates \
    libreoffice \
    poppler-utils \
    && rm -rf /var/lib/apt/lists/*

# Create non-root user
RUN groupadd -r docxmcp && useradd -r -g docxmcp -s /bin/bash -d /app docxmcp

WORKDIR /app
RUN chown -R docxmcp:docxmcp /app

# Copy binary from builder
COPY --from=builder /app/target/release/docx-mcp /usr/local/bin/docx-mcp
RUN chmod +x /usr/local/bin/docx-mcp

# Create working directories
RUN mkdir -p /tmp/docx-mcp /templates /out && \
    chown -R docxmcp:docxmcp /tmp/docx-mcp /templates /out

# Switch to non-root user
USER docxmcp

# Expose HTTP port (used when running in HTTP mode)
EXPOSE 3000

# Health check (checks binary is present and executable)
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
    CMD /usr/local/bin/docx-mcp --version

# Default environment:
# - HTTP disabled by default (use stdio mode).
# - Enable via DOCX_MCP_HTTP=true or --http-mode.
ENV RUST_LOG=info
ENV DOCX_MCP_TEMP=/tmp/docx-mcp
ENV DOCX_MCP_HTTP=false
ENV DOCX_MCP_HTTP_ADDRESS=0.0.0.0:3000
ENV DOCX_MCP_TEMPLATES_DIR=/templates
ENV DOCX_MCP_MAX_SIZE=104857600
ENV DOCX_MCP_MAX_DOCS=30

ENTRYPOINT ["/usr/local/bin/docx-mcp"]

# Default: stdio mode (for MCP clients).
# To run in HTTP mode, override CMD or set DOCX_MCP_HTTP=true.
CMD []
