# ChatCLI Operator - Multi-stage Docker build
# Must be built from the repo root: docker build -f operator/Dockerfile .
# This is required because go.mod uses: replace github.com/diillson/chatcli => ../

FROM golang:1.27.3 AS builder

WORKDIR /workspace

# Copy root module files (needed for replace directive)
COPY go.mod go.sum ./

# Copy operator module files and download dependencies (maximizes layer caching)
COPY operator/go.mod operator/go.sum ./operator/
WORKDIR /workspace/operator
RUN go mod download

# Copy source needed by the operator
WORKDIR /workspace
COPY proto/ proto/
COPY pkg/ pkg/
COPY config/ config/
COPY llm/ llm/
COPY models/ models/
COPY operator/main.go operator/main.go
COPY operator/api/ operator/api/
COPY operator/controllers/ operator/controllers/
COPY operator/internal/ operator/internal/
COPY operator/channels/ operator/channels/
COPY operator/web/ operator/web/

# Build (TARGETARCH is injected by docker buildx for multi-arch)
WORKDIR /workspace/operator
ARG TARGETARCH
RUN CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} go build -a -o manager main.go

# Runtime — Alpine is required because the SourceRepository controller
# needs git to clone and sync application repositories, and the ssh client
# for repositories with authType ssh.
# Pinned to exact patch version; Dependabot keeps this updated.
FROM alpine:3.24.2 AS runtime
RUN apk update && apk upgrade --no-cache && \
    apk add --no-cache \
        "libcrypto3>=3.5.8-r0" \
        "libssl3>=3.5.8-r0" \
        "libexpat>=2.8.4-r0" \
        "openssh-client-default>=10.3_p1-r1" \
        "pcre2>=10.49-r0" \
        "nghttp2-libs>=1.70.0-r0" \
        git ca-certificates tzdata && \
    adduser -D -u 65532 -g 65532 nonroot
WORKDIR /
COPY --from=builder /workspace/operator/manager .
USER 65532:65532

ENTRYPOINT ["/manager"]
