# syntax=docker/dockerfile:1

# Assumptions:
# 1. Previously ran auto-formatter
# 2. Previously ran linter (eslint)
# 3. Previously ran tests


# ---------------------------------------------
# -- Build stage
# ---------------------------------------------
# -- See https://hub.docker.com/_/node/
# -- Debug: docker run --rm -it node:20 /bin/bash
FROM node:20 AS buildStage

WORKDIR /app

RUN apt-get update -qq && \
  apt-get install -q -y curl tree unzip zip && \
  update-ca-certificates

# TODO: set up internal certificates here (so npm & pnpm work)

# TODO: set up ~/.npmrc for container here

# -- See https://github.com/pnpm/pnpm/releases
RUN npm install --global --silent pnpm@8.14.0 && \
  npm install --global --silent @angular/cli && \
  ng config --global cli.packageManager pnpm


# -- Copy sources (see also: .dockerignore)
COPY . .

# -- Get deps
RUN pnpm i


# TODO: decide on --cross-origin

# -- See https://angular.io/cli/build
# -- See angular.json for configuration names

# -- Debug build
RUN ng build \
--aot \
--base-href="/ui-debug/" \
--configuration development \
--delete-output-path \
--optimization=false \
--output-hashing=all \
--output-path build-output.debug \
--source-map=true


# -- Release build (speed optimized)
RUN ng build \
--aot \
--base-href="/ui/" \
--configuration production \
--delete-output-path \
--optimization=true \
--output-hashing=all \
--output-path build-output.release \
--source-map=true


# ---------------------------------------------
# -- Run stage
# ---------------------------------------------
FROM nginx:1.25-alpine as runStage
# -- NOTE: See ports in ./nginx/*-build.conf
# -- NOTE: See conf at /etc/nginx/nginx.conf & /etc/nginx/conf.d/*.conf
# -- Debug: docker run --rm -it nginx:1.25-alpine /bin/ash

# TODO: consider switch to https://hub.docker.com/r/nginxinc/nginx-unprivileged

USER root
WORKDIR /app

RUN update-ca-certificates && \
    apk update && \
    apk upgrade && \
    apk add --no-cache ca-certificates && \
    update-ca-certificates

# TODO: Add certs here if required

RUN rm -f /etc/nginx/conf.d/*.conf && \
    rm -f /usr/share/nginx/html/index.html

COPY --from=buildStage /app/nginx/*.conf /etc/nginx/conf.d/
COPY --from=buildStage /app/build-output.debug/browser/* /app/debug/
COPY --from=buildStage /app/build-output.release/browser/* /app/release/
