# syntax=docker/dockerfile:latest

#######################################################################
# Copyright (c) 2026 Huawei Technologies Co., Ltd.
# openFuyao is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#          http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
#######################################################################

# ==============================================================================
# Build stage: Compile the Go binary with static linking
# ==============================================================================
FROM golang:1.24.5-alpine3.21 AS builder

WORKDIR /workspace

# Copy go mod files first for better Docker layer caching.
# Dependencies are cached unless go.mod/go.sum change.
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod \
    go mod download

# Copy source code
COPY . .

# Build arguments for version information injection at build time.
# These are passed via `docker build --build-arg` and embedded into the binary
# using Go ldflags, allowing the binary to report its own version at runtime.
ARG VERSION=dev
ARG GIT_COMMIT=unknown
ARG BUILD_DATE=unknown

RUN --mount=type=cache,target=/go/pkg/mod \
    --mount=type=cache,target=/root/.cache/go-build \
    CGO_ENABLED=0 GOOS=linux go build \
    -ldflags="-s -w -X main.version=${VERSION} -X main.gitCommit=${GIT_COMMIT} -X main.buildDate=${BUILD_DATE}" \
    -o compliance-operator ./cmd/manager

# ==============================================================================
# Runtime stage: Minimal Alpine image with non-root user
# ==============================================================================
FROM alpine:3.21

WORKDIR /

RUN apk --no-cache add ca-certificates

COPY --from=builder --chmod=555 /workspace/compliance-operator .

RUN addgroup -S nonroot && adduser -S nonroot -G nonroot -u 65532

USER 65532:65532

# Version metadata labels - populated at build time via --build-arg
ARG VERSION=dev
ARG GIT_COMMIT=unknown
ARG BUILD_DATE=unknown

EXPOSE 8080 8081

LABEL version="${VERSION}" \
      git.commit="${GIT_COMMIT}" \
      build.date="${BUILD_DATE}" \
      description="Compliance Operator - Kubernetes cluster compliance scanning" \
      maintainer="openFuyao"

ENTRYPOINT ["/compliance-operator"]