# syntax=docker/dockerfile:1.7

FROM node:20-alpine AS base
ENV PNPM_HOME=/pnpm
ENV PATH=$PNPM_HOME:$PATH
WORKDIR /app
RUN apk add --no-cache libc6-compat && corepack enable

FROM base AS deps
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml turbo.json ./
COPY apps/web/package.json apps/web/package.json
COPY apps/server/package.json apps/server/package.json
COPY packages/shared/package.json packages/shared/package.json
RUN pnpm config set fetch-retries 5 \
    && pnpm config set fetch-retry-mintimeout 10000 \
    && pnpm config set fetch-retry-maxtimeout 120000 \
    && pnpm install --frozen-lockfile

FROM deps AS builder
ARG NEXT_PUBLIC_API_URL=/api/v1
ARG NEXT_API_PROXY_TARGET=
ARG APP_VERSION=unknown
ARG APP_BUILD_TIME=
ARG APP_IMAGE_TAG=
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
ENV NEXT_API_PROXY_TARGET=$NEXT_API_PROXY_TARGET
ENV NEXT_PUBLIC_APP_VERSION=$APP_VERSION
ENV NEXT_PUBLIC_APP_BUILD_TIME=$APP_BUILD_TIME
ENV NEXT_PUBLIC_APP_IMAGE_TAG=$APP_IMAGE_TAG
ENV NEXT_TELEMETRY_DISABLED=1
ENV NODE_ENV=production
COPY packages/shared packages/shared
COPY apps/web apps/web
RUN pnpm --filter @ftb/shared build
RUN pnpm --filter web build

FROM base AS runner
ARG NEXT_PUBLIC_API_URL=/api/v1
ARG NEXT_API_PROXY_TARGET=
ARG APP_VERSION=unknown
ARG APP_BUILD_TIME=
ARG APP_IMAGE_TAG=
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
ENV NEXT_API_PROXY_TARGET=$NEXT_API_PROXY_TARGET
ENV NEXT_PUBLIC_APP_VERSION=$APP_VERSION
ENV NEXT_PUBLIC_APP_BUILD_TIME=$APP_BUILD_TIME
ENV NEXT_PUBLIC_APP_IMAGE_TAG=$APP_IMAGE_TAG
ENV NEXT_TELEMETRY_DISABLED=1
ENV NODE_ENV=production
LABEL org.opencontainers.image.revision=$APP_VERSION
LABEL org.opencontainers.image.created=$APP_BUILD_TIME
LABEL org.opencontainers.image.ref.name=$APP_IMAGE_TAG
COPY --from=builder /app/package.json ./package.json
COPY --from=builder /app/pnpm-lock.yaml ./pnpm-lock.yaml
COPY --from=builder /app/pnpm-workspace.yaml ./pnpm-workspace.yaml
COPY --from=builder /app/turbo.json ./turbo.json
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/packages/shared ./packages/shared
COPY --from=builder /app/apps/web ./apps/web
RUN chown -R node:node /app
USER node
EXPOSE 3000
CMD ["pnpm", "--filter", "web", "start"]
