# syntax=docker/dockerfile:1

# ---------- Build stage ----------
FROM --platform=$BUILDPLATFORM golang:1.21-alpine AS builder

ARG TARGETOS
ARG TARGETARCH

WORKDIR /app

# 复制依赖描述文件
COPY go.mod go.sum* ./

# 复制源码与资源
COPY main.go ./
COPY templates/ ./templates/
COPY static/ ./static/

# 自动补齐/校正 go.sum，下载依赖
RUN go mod tidy

# 构建静态二进制（去掉 debug 符号，体积更小）
RUN CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH:-amd64} \
    go build -trimpath -ldflags="-s -w" -o /out/server .

# ---------- Runtime stage ----------
FROM alpine:3.19

# 时区与根证书
RUN apk --no-cache add ca-certificates tzdata wget && \
    addgroup -S app && adduser -S app -G app
ENV TZ=Asia/Shanghai

WORKDIR /app
COPY --from=builder /out/server /app/server

# 以非 root 用户运行
USER app

EXPOSE 8080

# 健康检查
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
    CMD wget -q --spider http://127.0.0.1:8080/ || exit 1

ENTRYPOINT ["/app/server"]
