FROM node:22.13.1-alpine3.20 AS base

ARG LABS_FRONTEND_VERSION=unknown
ARG LABS_FRONTEND_REGION=unknown
ENV LABS_FRONTEND_VERSION=${LABS_FRONTEND_VERSION}
ENV LABS_FRONTEND_REGION=${LABS_FRONTEND_REGION}

LABEL org.opencontainers.image.version=${LABS_FRONTEND_VERSION}
LABEL org.opencontainers.image.source=https://github.com/pingcap-inc/labs.tidb.io/frontend

FROM base AS deps
# 1. Install dependencies only when needed

# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache --virtual .gyp  \
      libc6-compat  \
      py3-pip  \
      pkgconfig  \
      pixman-dev  \
      cairo-dev  \
      pango-dev  \
      build-base \
      && ln -sf python3 /usr/bin/python \
      && ln -sf pip3 /usr/bin/pip

WORKDIR /tidb-labs

COPY package.json .
COPY pnpm-*.yaml .

RUN npm install -g corepack@latest
RUN corepack enable pnpm
RUN pnpm i --frozen-lockfile

RUN apk del .gyp

FROM base AS builder
# 2. Build

WORKDIR /tidb-labs

COPY --from=deps /tidb-labs/node_modules ./node_modules

ADD src ./src
ADD package.json .
ADD pnpm-*.yaml .
ADD eslint.*.*s .
ADD next.*.*s .
ADD next-*.*s .
ADD postcss.config.*s .
ADD sentry.*.config.*s .
ADD tailwind.config.*s .
ADD tsconfig.json .

RUN npm install -g corepack@latest
RUN corepack enable pnpm

RUN --mount=type=secret,id=env-${LABS_FRONTEND_REGION},dst=/tidb-labs/.env  \
    NODE_OPTIONS="--max_old_space_size=4096" \
    pnpm run build

RUN rm ./.next/standalone/.env

FROM base AS runner

ARG GIT_COMMIT_SHA=unknown
ENV GIT_COMMIT_SHA=${GIT_COMMIT_SHA}

WORKDIR /tidb-labs

COPY --from=builder --chown=nextjs:nodejs /tidb-labs/.next/standalone .
COPY --from=builder /tidb-labs/.next/static ./.next/static

# Runtime env
ENV NODE_ENV=production
ENV PORT=3000
ENV HOSTNAME=0.0.0.0

RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001

RUN chown -R nextjs .

USER nextjs
EXPOSE 3000

CMD ["node", "--enable-source-maps", "server.js"]
