# syntax=docker/dockerfile:1.7

## Frontend
## =========================

ARG NGINX_VERSION=1.29.8

FROM node:22-alpine AS frontend-dependencies

WORKDIR /workspace/Frontend

RUN corepack enable && corepack prepare pnpm@9.0.0 --activate

COPY Frontend/package.json Frontend/pnpm-lock.yaml Frontend/tsconfig.json Frontend/vite.config.ts ./
RUN pnpm install --frozen-lockfile

FROM frontend-dependencies AS frontend-build

ENV NODE_ENV=production

COPY Frontend/ ./

RUN pnpm build:static

## Proxy
## =========================

FROM alpine:3.22 AS precompressed-assets

RUN apk add --no-cache brotli gzip

WORKDIR /workspace

COPY Loader ./html/__loader
COPY --from=frontend-build /workspace/Frontend/dist/client ./html

RUN find ./html -type f \( \
  -name '*.html' -o \
  -name '*.css' -o \
  -name '*.js' -o \
  -name '*.json' -o \
  -name '*.svg' -o \
  -name '*.txt' -o \
  -name '*.xml' -o \
  -name '*.webmanifest' \
\) -exec gzip -kf -9 {} \; \
  && find ./html -type f \( \
  -name '*.html' -o \
  -name '*.css' -o \
  -name '*.js' -o \
  -name '*.json' -o \
  -name '*.svg' -o \
  -name '*.txt' -o \
  -name '*.xml' -o \
  -name '*.webmanifest' \
\) -exec brotli -kf -Z {} \;

FROM alpine:3.22 AS brotli-modules

ARG NGINX_VERSION

RUN apk add --no-cache \
  alpine-sdk \
  cmake \
  git \
  linux-headers \
  openssl-dev \
  pcre2-dev \
  wget \
  zlib-dev

WORKDIR /tmp

RUN wget -O "nginx-${NGINX_VERSION}.tar.gz" "https://nginx.org/download/nginx-${NGINX_VERSION}.tar.gz" \
  && tar -xzf "nginx-${NGINX_VERSION}.tar.gz" \
  && git clone --recurse-submodules https://github.com/google/ngx_brotli.git

WORKDIR /tmp/nginx-${NGINX_VERSION}

RUN cd /tmp/ngx_brotli/deps/brotli \
  && mkdir -p out \
  && cd out \
  && cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=OFF -DCMAKE_C_FLAGS="-fPIC" -DCMAKE_CXX_FLAGS="-fPIC" .. \
  && cmake --build . --config Release -j"$(getconf _NPROCESSORS_ONLN)" \
  && cd /tmp/nginx-${NGINX_VERSION} \
  && ./configure --with-compat --add-dynamic-module=/tmp/ngx_brotli \
  && make modules

FROM nginx:${NGINX_VERSION}-alpine AS production

COPY Proxy/Local/nginx.conf /etc/nginx/nginx.conf
COPY Proxy/Local/default.conf /etc/nginx/conf.d/default.conf
COPY --from=brotli-modules /tmp/nginx-${NGINX_VERSION}/objs/ngx_http_brotli_filter_module.so /usr/lib/nginx/modules/
COPY --from=brotli-modules /tmp/nginx-${NGINX_VERSION}/objs/ngx_http_brotli_static_module.so /usr/lib/nginx/modules/
COPY --from=precompressed-assets /workspace/html /usr/share/nginx/html

EXPOSE 80

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