# syntax=docker/dockerfile:1.7

# ---- build stage -----------------------------------------------------------
FROM golang:1.25-alpine AS build

WORKDIR /src

# git is useful for `go mod download` of VCS-pinned modules; harmless otherwise.
RUN apk add --no-cache ca-certificates git

# Cache dependencies before copying the rest of the source.
COPY go.mod go.sum ./
RUN go mod download

COPY . .

ARG VERSION=dev
ARG COMMIT=unknown
ARG BUILD_TIME=

RUN CGO_ENABLED=0 GOOS=linux go build -trimpath \
        -ldflags "-s -w \
          -X gitea.lab.audasmedia.com.au/sam/email_agent/internal/version.Version=${VERSION} \
          -X gitea.lab.audasmedia.com.au/sam/email_agent/internal/version.Commit=${COMMIT} \
          -X gitea.lab.audasmedia.com.au/sam/email_agent/internal/version.BuildTime=${BUILD_TIME}" \
        -o /out/email-agent ./cmd/email-agent

# ---- runtime stage ---------------------------------------------------------
# Alpine (not distroless) so the bundled healthcheck and `sh` are available.
FROM alpine:3.21

RUN apk add --no-cache ca-certificates tzdata \
    && addgroup -g 10001 -S app \
    && adduser -u 10001 -S -G app -H -s /sbin/nologin app \
    && mkdir -p /data \
    && chown app:app /data

COPY --from=build /out/email-agent /usr/local/bin/email-agent

USER app

EXPOSE 8790

ENV EMAIL_AGENT_ADDR=":8790" \
    EMAIL_AGENT_DB_PATH="/data/email_agent.db"

VOLUME ["/data"]

HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
    CMD ["/usr/local/bin/email-agent", "-healthcheck"]

ENTRYPOINT ["/usr/local/bin/email-agent"]
