# Site builder
FROM node:26.7-alpine3.23 AS frontend-builder

WORKDIR /frontend

RUN npm install -g pnpm@11.1.2

COPY ./frontend/package.json ./
COPY ./frontend/pnpm-lock.yaml ./

RUN pnpm ci

COPY ./frontend/public ./public
COPY ./frontend/src ./src
COPY ./frontend/eslint.config.js ./
COPY ./frontend/index.html ./
COPY ./frontend/tsconfig.json ./
COPY ./frontend/tsconfig.app.json ./
COPY ./frontend/tsconfig.node.json ./
COPY ./frontend/vite.config.ts ./

RUN pnpm run build

# Builder
FROM golang:1.26-alpine3.23 AS builder

ARG VERSION
ARG COMMIT_HASH
ARG BUILD_TIMESTAMP
ARG LDFLAGS
ARG BUILD_TAGS

WORKDIR /tinyauth

COPY go.mod ./
COPY go.sum ./

RUN go mod download

COPY ./cmd ./cmd/
COPY ./internal ./internal
COPY ./pkg ./pkg
COPY --from=frontend-builder /frontend/dist ./internal/assets/dist

RUN CGO_ENABLED=0 go build -tags "${BUILD_TAGS}" -ldflags "${LDFLAGS} \
    -X github.com/tinyauthapp/tinyauth/internal/model.Version=${VERSION} \
    -X github.com/tinyauthapp/tinyauth/internal/model.CommitHash=${COMMIT_HASH} \
    -X github.com/tinyauthapp/tinyauth/internal/model.BuildTimestamp=${BUILD_TIMESTAMP}" \
    -o tinyauth ./cmd/tinyauth

# Make the data directory with a non-root user
RUN addgroup tinyauth && adduser -DH tinyauth -G tinyauth
RUN mkdir -p /data/resources /data/oidc /data/tailscale
RUN chown -R tinyauth:tinyauth /data

# Runner
FROM gcr.io/distroless/static-debian12:latest AS runner

WORKDIR /tinyauth

COPY --from=builder /tinyauth/tinyauth ./

# Since it's distroless, we need to copy the data directory from the builder stage
COPY --from=builder /data /data

EXPOSE 3000

VOLUME ["/data"]

# Tell tinyauth that it's running in a container and where to find the data directory
ENV RUNTIME_ENV=docker

ENV PATH=$PATH:/tinyauth

HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 CMD ["tinyauth", "healthcheck"]

ENTRYPOINT ["tinyauth"]
