# ---------------------------------------------------------------------------- #
# Base image for building from
FROM node:18-alpine AS base
# ---------------------------------------------------------------------------- #
# Install dependencies of project
# Choosing the right package manager
FROM base AS deps
RUN apk add --no-cache libc6-compat git
WORKDIR /app

ARG YARN_CACHE_FOLDER=/var/yarn/.cache
RUN yarn config set cache-folder $YARN_CACHE_FOLDER # just to be explicit
RUN --mount=type=cache,mode=0777,target=$YARN_CACHE_FOLDER yarn cache list

COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./
RUN --mount=type=cache,mode=0777,target=$YARN_CACHE_FOLDER \
  if [ -f yarn.lock ]; then YARN_CACHE_FOLDER=$YARN_CACHE_FOLDER yarn --frozen-lockfile; \
  elif [ -f package-lock.json ]; then npm ci; \
  elif [ -f pnpm-lock.yaml ]; then yarn global add pnpm && pnpm i --frozen-lockfile; \
  else echo "Lockfile not found." && exit 1; \
  fi
# ---------------------------------------------------------------------------- #
# Rebuild the source code only when needed
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .

RUN yarn build
# ---------------------------------------------------------------------------- #
FROM nginx:1.23.1-alpine

COPY ./nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /app/dist /usr/share/nginx/html

RUN touch /var/run/nginx.pid
RUN chown -R nginx:nginx /var/run/nginx.pid /var/cache/nginx /var/log/nginx /etc/nginx/conf.d

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]
