# =========================
# Builder stage (Alpine)
# =========================
FROM golang:1.25-alpine AS builder

RUN apk add --no-cache ca-certificates tzdata

# All project files under /app
WORKDIR /app
ADD . .

# Git tag/version passed from build args, e.g. v1.0.0
ARG VERSION=dev

# Buildx injects these automatically for multi-arch builds
ARG TARGETOS
ARG TARGETARCH

# Adjust this to your real main package directory
# e.g. /app/cmd/drip-server if different
WORKDIR /app/cmd/drip

# main.version should match the version variable in your Go code
RUN env CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH:-amd64} \
    go build -v -trimpath \
      -ldflags "-s -w -X main.version=${VERSION}" \
      -o /app/bin/drip

# =========================
# Runtime stage (Alpine)
# =========================
FROM alpine:3.22

RUN apk add --no-cache ca-certificates tzdata curl && \
    update-ca-certificates

# Everything lives under /app in runtime image
WORKDIR /app

# Optional but nice to have: certs + timezone data
COPY --from=builder /etc/ssl/certs /etc/ssl/certs
COPY --from=builder /usr/share/zoneinfo /usr/share/zoneinfo

# Copy the built binary into /app
COPY --from=builder /app/bin/drip /app/drip

# Non-root user
RUN addgroup -S drip && adduser -S -G drip drip && \
    chown -R drip:drip /app
USER drip

EXPOSE 80 443 8080 20000-20100

HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD curl -fsS "http://localhost:${PORT:-8080}/health" >/dev/null || exit 1

ENTRYPOINT ["/app/drip"]
CMD ["server", "--port", "8080"]
