#!/usr/bin/make -f

DESTDIR = $(CURDIR)/debian/element-desktop
APPDIR = $(DESTDIR)/usr/lib/element-desktop

%:
	dh $@

override_dh_auto_build:
	# Build Element Web from this same immutable monorepo ref, then compile the
	# desktop wrapper. Do not invoke electron-builder: it would bundle Electron.
	pnpm nx build element-web
	rm -rf apps/desktop/webapp
	cp -a apps/web/webapp apps/desktop/webapp
	cp apps/desktop/element.io/release/config.json apps/desktop/webapp/config.json
	pnpm -C apps/desktop run asar-webapp
	pnpm nx run element-desktop:build:ts
	pnpm nx run element-desktop:build:res
	# Produce a production dependency closure without devDependency Electron.
	rm -rf debian/element-deploy
	pnpm --filter element-desktop deploy --prod --legacy debian/element-deploy
	# A peer-resolution layout may expose the workspace's dev-only Electron to
	# the deployed tree. Remove it explicitly; Electron imports resolve to the
	# shared executable's built-in module at runtime.
	rm -rf debian/element-deploy/node_modules/electron

override_dh_auto_install:
	install -d $(APPDIR) $(DESTDIR)/usr/bin
	cp -a debian/element-deploy/package.json debian/element-deploy/node_modules $(APPDIR)/
	cp -a apps/desktop/lib $(APPDIR)/
	install -m 0644 apps/desktop/webapp.asar $(APPDIR)/webapp.asar
	install -D -m 0644 apps/desktop/build/icon.png $(APPDIR)/build/icon.png
	# matrix-seshat is optional upstream and lives outside pnpm dependencies.
	# Assert that neither it nor any Electron runtime entered the payload.
	test ! -e $(APPDIR)/node_modules/matrix-seshat
	test ! -e $(APPDIR)/node_modules/electron
	test ! -e $(APPDIR)/node_modules/electron/dist
	! find $(APPDIR) -type f -name '*.node' -print -quit | grep -q .
	printf '%s\n' \
		'#!/bin/sh' \
		'set -eu' \
		'unset ELECTRON_RUN_AS_NODE' \
		'exec /usr/lib/electron-runtime-44/electron /usr/lib/element-desktop --no-update "$$@"' \
		> $(DESTDIR)/usr/bin/element-desktop
	chmod 0755 $(DESTDIR)/usr/bin/element-desktop
	install -D -m 0644 debian/element-desktop.desktop \
		$(DESTDIR)/usr/share/applications/element-desktop.desktop
	install -D -m 0644 apps/desktop/build/icon.png \
		$(DESTDIR)/usr/share/icons/hicolor/512x512/apps/element-desktop.png

override_dh_auto_test:
	# Runtime behavior is covered by test/test-shared-electron-element-desktop.sh.
