FROM node:22-bookworm AS ui-builder

RUN npm install -g pnpm
WORKDIR /src/ui

COPY ui/package.json ui/pnpm-lock.yaml ./
RUN pnpm install --frozen-lockfile

COPY ui/ ./
RUN pnpm run build

FROM golang:1.26.1-bookworm AS builder

WORKDIR /src

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

COPY . .
COPY --from=ui-builder /src/internal/app/ui/dist ./internal/app/ui/dist

RUN set -eu; \
    VERSION_TAG="$(git describe --tags --exact-match 2>/dev/null || echo dev)"; \
    COMMIT_SHA="$(git rev-parse --short HEAD 2>/dev/null || echo unknown)"; \
    BUILD_DATE="$(date -u +%Y-%m-%dT%H:%M:%SZ)"; \
    CGO_ENABLED=0 GOOS=linux go build -trimpath \
      -ldflags="-s -w \
        -X git.warky.dev/wdevs/amcs/internal/buildinfo.Version=${VERSION_TAG} \
        -X git.warky.dev/wdevs/amcs/internal/buildinfo.TagName=${VERSION_TAG} \
        -X git.warky.dev/wdevs/amcs/internal/buildinfo.Commit=${COMMIT_SHA} \
        -X git.warky.dev/wdevs/amcs/internal/buildinfo.BuildDate=${BUILD_DATE}" \
      -o /out/amcs-server ./cmd/amcs-server; \
    CGO_ENABLED=0 GOOS=linux go build -trimpath \
      -ldflags="-s -w \
        -X git.warky.dev/wdevs/amcs/internal/buildinfo.Version=${VERSION_TAG} \
        -X git.warky.dev/wdevs/amcs/internal/buildinfo.TagName=${VERSION_TAG} \
        -X git.warky.dev/wdevs/amcs/internal/buildinfo.Commit=${COMMIT_SHA} \
        -X git.warky.dev/wdevs/amcs/internal/buildinfo.BuildDate=${BUILD_DATE}" \
      -o /out/amcs-migrate-config ./cmd/amcs-migrate-config

FROM debian:bookworm-slim

RUN apt-get update \
    && apt-get install -y --no-install-recommends ca-certificates \
    && rm -rf /var/lib/apt/lists/* \
    && useradd --system --create-home --uid 10001 appuser

WORKDIR /app

COPY --from=builder /out/amcs-server /app/amcs-server
COPY --from=builder /out/amcs-migrate-config /app/amcs-migrate-config
COPY --chown=appuser:appuser configs /app/configs

USER appuser

EXPOSE 8080

ENV AMCS_CONFIG=/app/configs/docker.yaml

ENTRYPOINT ["/app/amcs-server"]
