# syntax=docker/dockerfile:1.7

FROM golang:1.26.10-alpine3.24 AS builder
WORKDIR /src

COPY app/go.mod app/go.sum ./
RUN go mod download

COPY app/ ./

RUN CGO_ENABLED=0 GOOS=linux go build \
    -ldflags="-s -w" \
    -trimpath \
    -o /out/messenger ./cmd/messenger

RUN CGO_ENABLED=0 GOOS=linux go build \
    -ldflags="-s -w" \
    -trimpath \
    -o /out/cachebench ./cmd/cachebench

FROM golang:1.26.10-alpine3.24 AS goose-builder
RUN CGO_ENABLED=0 go install -trimpath -ldflags="-s -w" \
    -tags='no_clickhouse no_libsql no_mssql no_mysql no_sqlite3 no_vertica no_ydb' \
    github.com/pressly/goose/v3/cmd/goose@v3.26.0

FROM alpine:3.24.3 AS migrate
COPY --from=goose-builder /go/bin/goose /usr/local/bin/goose
COPY migrations /migrations
ENTRYPOINT ["/bin/sh", "-c", "exec goose -dir /migrations postgres \"$(cat \"$DATABASE_URL_FILE\")\" up"]

FROM alpine:3.24.3 AS cachebench
COPY --from=builder /out/cachebench /usr/local/bin/cachebench
ENTRYPOINT ["/usr/local/bin/cachebench"]

FROM alpine:3.24.3

RUN apk add --no-cache ca-certificates && \
    addgroup -S app && \
    adduser -S -G app -H app

WORKDIR /app

COPY --from=builder /out/messenger /app/messenger

USER app

EXPOSE 8080
STOPSIGNAL SIGTERM

HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
    CMD wget --quiet --spider "http://127.0.0.1:${APP_PORT:-8080}/health/ready" || exit 1

ENTRYPOINT ["/app/messenger"]
