#!/usr/bin/make -f

export HOME = $(CURDIR)/debian/fakehome
export XDG_CACHE_HOME = $(CURDIR)/debian/fakehome/.cache
export npm_config_cache = $(CURDIR)/debian/fakehome/.npm
export CI = true
export NODE_OPTIONS = --max-old-space-size=4096

APPDIR = debian/tmp/usr/share/rekono
BUILD_TOOLS = $(CURDIR)/debian/build-tools
PNPM = $(BUILD_TOOLS)/node_modules/.bin/pnpm
PNPM_VERSION = $(shell node -p "require('./frontend/package.json').packageManager.split('@')[1]")

%:
	dh $@

override_dh_auto_configure:
	mkdir -p $(HOME)
	npm install --prefix $(BUILD_TOOLS) --no-save --no-audit --no-fund pnpm@$(PNPM_VERSION)

override_dh_auto_build:
	# Frontend: produces the self-contained Nitro bundle in frontend/.output
	cd frontend && $(PNPM) install --frozen-lockfile --prod --ignore-scripts
	cd frontend && $(PNPM) run build
	# Email templates: produces HTML templates used by the backend
	cd email-templates && $(PNPM) install --frozen-lockfile --prod --ignore-scripts
	cd email-templates && $(PNPM) run build

override_dh_auto_install:
	# Backend source
	mkdir -p $(APPDIR)/backend
	cp -a backend/. $(APPDIR)/backend/
	rm -rf $(APPDIR)/backend/tests
	# Frontend bundle
	mkdir -p $(APPDIR)/frontend
	cp -a frontend/.output/. $(APPDIR)/frontend/
	# Override backend configuration with custom one
	install -D -m 0644 debian/etc/config.yaml $(APPDIR)/config.yaml
	# Launcher and helpers
	install -D -m 0755 debian/bin/rekono debian/tmp/usr/bin/rekono
	install -d debian/tmp/usr/libexec/rekono
	install -m 0755 debian/libexec/rekono-* debian/tmp/usr/libexec/rekono/
	install -D -m 0644 debian/uv.sha256 $(APPDIR)/uv.sha256
	# systemd units
	install -d debian/tmp/usr/lib/systemd/system
	install -m 0644 debian/systemd/rekono.target debian/tmp/usr/lib/systemd/system/
	install -m 0644 debian/systemd/*.service debian/tmp/usr/lib/systemd/system/
	install -D -m 0644 debian/systemd/executions-capabilities.conf \
	    debian/tmp/usr/lib/systemd/system/rekono-worker@executions.service.d/capabilities.conf
	# Configuration
	install -D -m 0644 debian/etc/nginx.conf debian/tmp/etc/rekono/nginx.conf
	install -D -m 0644 debian/etc/valkey.conf debian/tmp/etc/rekono/valkey.conf
	install -D -m 0644 debian/etc/default debian/tmp/etc/default/rekono
	# Lets the desktop user start and stop Rekono without a password prompt.
	install -D -m 0644 debian/polkit/49-rekono.rules \
	    debian/tmp/usr/share/polkit-1/rules.d/49-rekono.rules
	# Desktop integration
	install -D -m 0644 debian/rekono.desktop \
	    debian/tmp/usr/share/applications/rekono.desktop
	install -d debian/tmp/usr/share/icons/hicolor
	cp -a debian/icons/. debian/tmp/usr/share/icons/hicolor/

override_dh_installsystemd:
	dh_installsystemd --no-enable --no-start

override_dh_auto_clean:
	rm -rf frontend/.output frontend/.nuxt frontend/node_modules
	rm -rf email-templates/node_modules
	rm -f backend/platforms/email/templates/*.html
	rm -rf $(BUILD_TOOLS) $(CURDIR)/debian/fakehome
