# syntax=docker/dockerfile:1

# Compile stage. Dependencies are vendored, so the build needs no module proxy
# and the same source tree produces the same binary from a clean clone.
FROM golang:1.25.1-alpine3.22@sha256:b6ed3fd0452c0e9bcdef5597f29cc1418f61672e9d3a2f55bf02e7222c014abd AS build

WORKDIR /src
ENV CGO_ENABLED=0 \
    GOTOOLCHAIN=local \
    GOFLAGS=-mod=vendor

COPY go.mod go.sum ./
COPY vendor ./vendor
COPY cmd ./cmd
COPY internal ./internal

ARG VERSION=1.0.0
ARG REVISION=unknown
RUN go build \
        -trimpath \
        -buildvcs=false \
        -ldflags="-s -w -buildid= -X main.version=${VERSION} -X main.revision=${REVISION}" \
        -o /out/messenger \
        ./cmd/messenger \
    && go build \
        -trimpath \
        -buildvcs=false \
        -ldflags="-s -w -buildid= -X main.revision=${REVISION}" \
        -o /out/migrate \
        ./cmd/migrate

# Runtime stage: minimal Alpine pinned by digest, no shell tooling and no
# package manager calls. The process runs as the unprivileged uid 10001.
FROM alpine:3.22.1@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1 AS runtime

LABEL org.opencontainers.image.title="mtusi-messenger-lab3" \
      org.opencontainers.image.description="MTUSI highload lab 3: HAProxy, replicated API, shared PostgreSQL and Valkey" \
      org.opencontainers.image.version="1.0.0"

WORKDIR /app
COPY --from=build --chown=10001:10001 /out/messenger /app/messenger
COPY --from=build --chown=10001:10001 /out/migrate /app/migrate

USER 10001:10001
EXPOSE 8080

ENV APP_HOST=0.0.0.0 \
    APP_PORT=8080 \
    APP_ENV=lab \
    LOG_LEVEL=info \
    SESSION_TTL_SECONDS=3600 \
    SHUTDOWN_TIMEOUT_SECONDS=6 \
    SHUTDOWN_DRAIN_SECONDS=3

# The same binary implements -healthcheck, so the image needs no curl/wget and
# the probe runs as the unprivileged user.
HEALTHCHECK --interval=3s --timeout=2s --start-period=10s --retries=3 \
    CMD ["/app/messenger", "-healthcheck"]

ENTRYPOINT ["/app/messenger"]
