FROM node:20-slim AS base

ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"

RUN corepack enable

WORKDIR /app

# pnpm >=10 blocks dependency lifecycle scripts by default and then FAILS the
# install with ERR_PNPM_IGNORED_BUILDS (pnpm 12 still does this even with
# onlyBuiltDependencies in pnpm-workspace.yaml, and --no-ignore-scripts does not
# suppress the error either). esbuild's postinstall places the platform binary
# the Vite build needs, so approve pending build scripts non-interactively.
# --frozen-lockfile is dropped because the added config keys change the lockfile
# hash and would fail the install outright.
COPY ./frontend/pnpm-workspace.yaml ./frontend/package.json ./frontend/pnpm-lock.yaml /app/
RUN pnpm install --ignore-scripts \
 && pnpm approve-builds --all \
 && pnpm rebuild

FROM base AS build

COPY ./frontend/ /app/
RUN pnpm run build

# NOTE: upstream pinned ghcr.io/circleous/httpd, but ghcr.io is not
# anonymously pullable from this host ("failed to fetch oauth token: denied").
# The bundled httpd.conf only uses stock Apache 2.4 modules, so the official
# Docker Hub httpd:2.4 image is a drop-in replacement.
FROM httpd:2.4

WORKDIR /app

COPY ./kauth /app/kauth/

RUN set eux; \
	apt-get update; \
	apt-get install -y --no-install-recommends \
		openssh-server \
		pkg-config \
		gcc \
		curl \
		make \
		lua5.3 \
		liblua5.3-dev \
		libsodium-dev \
		libsqlite3-dev \
		luarocks \
	; \
    luarocks-5.3 install lua-cjson; \
    luarocks-5.3 install lsqlite3; \
    luarocks-5.3 install bcrypt; \
	cd kauth; \
	luarocks-5.3 make; \
	cd ..; \
	rm -rf kauth;\
	apt-get remove -y \
		pkg-config \
		gcc \
		make \
		lua5.3 \
		liblua5.3-dev; \
	echo root:${PASSWORD} | chpasswd \
	echo "PasswordAuthentication yes" >> /etc/ssh/sshd_config; \
	echo "PermitRootLogin yes" >> /etc/ssh/sshd_config; \
	service ssh start; \
	apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false;		

COPY httpd-foreground /usr/local/bin/
COPY ./httpd.conf /usr/local/apache2/conf/httpd.conf
COPY --chown=www-data:www-data ./fjb.db /app/data/fjb.db
COPY --from=build /app/dist /usr/local/apache2/htdocs
COPY ./src/ /app/lua/

RUN sed -ri "s/SECRETSECRETSECRETSECRETSECRETSE/$(openssl rand -hex 16)/g" /app/lua/secret.lua && \
	chmod 644 /app/lua/secret.lua

EXPOSE 80
CMD ["httpd-foreground"]
