# Wails Server Mode Dockerfile
# Multi-stage build for a minimal image.
#
# Defaults produce a pure-Go, fully static binary on a distroless/static base:
# the smallest, most secure image, and correct for the default (CGO-free) app.
#
# If your app needs CGO, override the build args, e.g.:
#   docker build --build-arg CGO_ENABLED=1 \
#                --build-arg GO_IMAGE=golang:bookworm \
#                --build-arg RUNTIME_IMAGE=gcr.io/distroless/base-debian12 \
#                -f build/docker/Dockerfile.server .
# CGO needs a C toolchain in the builder and a libc in the runtime image; keep
# the builder and runtime libc compatible (a glibc builder -> a glibc runtime).
# The Taskfile passes these through: task build:docker CGO_ENABLED=1 GO_IMAGE=... RUNTIME_IMAGE=...

ARG GO_IMAGE=golang:alpine
ARG RUNTIME_IMAGE=gcr.io/distroless/static-debian12
ARG CGO_ENABLED=0

# Build stage
FROM ${GO_IMAGE} AS builder
ARG CGO_ENABLED

WORKDIR /app

# Install build dependencies: git always; a C compiler only when CGO is enabled.
# Supports both apk (alpine) and apt (debian/bookworm) base images.
RUN if command -v apk >/dev/null 2>&1; then \
        apk add --no-cache git $([ "$CGO_ENABLED" = "1" ] && echo gcc musl-dev); \
    else \
        apt-get update && apt-get install -y --no-install-recommends git $([ "$CGO_ENABLED" = "1" ] && echo gcc libc6-dev) && rm -rf /var/lib/apt/lists/*; \
    fi

# Copy source code
COPY . .

# Remove local replace directive if present (for production builds)
RUN sed -i '/^replace/d' go.mod || true

# Download dependencies
RUN go mod tidy

# Build the production server binary.
# - server,production tags: HTTP server mode with production code paths (no dev
#   logger/asset middleware), matching the desktop production build.
# - CGO_ENABLED defaults to 0 for a fully static binary (distroless/static);
#   override with --build-arg CGO_ENABLED=1 (see header) for CGO apps.
RUN CGO_ENABLED=${CGO_ENABLED} go build -tags server,production -trimpath -buildvcs=false -ldflags="-s -w" -o server .

# Runtime stage - minimal image
FROM ${RUNTIME_IMAGE}

# Copy the binary
COPY --from=builder /app/server /server

# Copy frontend assets
COPY --from=builder /app/frontend/dist /frontend/dist

# Expose the default port
EXPOSE 8080

# Bind to all interfaces (required for Docker)
# Can be overridden at runtime with -e WAILS_SERVER_HOST=...
ENV WAILS_SERVER_HOST=0.0.0.0

# Run the server
ENTRYPOINT ["/server"]
