#!/usr/bin/make -f

DESTDIR = $(CURDIR)/debian/super-productivity
APPDIR  = $(DESTDIR)/usr/lib/super-productivity
HELPER  = $(CURDIR)/wayland-idle-helper-src
ICONSIZES = 16x16 32x32 48x48 64x64 128x128 256x256 512x512 1024x1024

export CARGO_HOME = $(CURDIR)/debian/cargo-home

%:
	dh $@

override_dh_auto_build:
	# The application resources come from the checksum-pinned outer build. The
	# only thing compiled here is upstream's ext-idle-notify helper, built from
	# the Rust sources shipped in this release against its own lockfile.
	cargo build --release --locked --manifest-path $(HELPER)/Cargo.toml
	test -x $(HELPER)/target/release/wayland-idle-helper

override_dh_auto_install:
	install -d $(APPDIR) $(DESTDIR)/usr/bin
	install -m 0644 app-payload/app.asar $(APPDIR)/app.asar
	install -m 0755 $(HELPER)/target/release/wayland-idle-helper $(APPDIR)/wayland-idle-helper
	printf '%s\n' \
		'#!/bin/sh' \
		'set -eu' \
		'unset ELECTRON_RUN_AS_NODE' \
		'exec /usr/lib/electron-runtime-43/electron /usr/lib/super-productivity/app.asar "$$@"' \
		> $(DESTDIR)/usr/bin/super-productivity
	chmod 0755 $(DESTDIR)/usr/bin/super-productivity
	install -D -m 0644 debian/super-productivity.desktop \
		$(DESTDIR)/usr/share/applications/super-productivity.desktop
	set -e; for size in $(ICONSIZES); do \
		install -D -m 0644 icons/$$size.png \
			$(DESTDIR)/usr/share/icons/hicolor/$$size/apps/super-productivity.png; \
	done
	# Enforce the application/runtime ownership boundary: the shared runtime owns
	# every Electron and Chromium object, and APT owns updates.
	test ! -e $(APPDIR)/app-update.yml
	test ! -e $(APPDIR)/app.asar.unpacked
	! find $(APPDIR) -type f \( -name electron -o -name chrome-sandbox \
		-o -name chrome_crashpad_handler -o -name resources.pak \
		-o -name chrome_100_percent.pak -o -name chrome_200_percent.pak \
		-o -name icudtl.dat -o -name snapshot_blob.bin \
		-o -name v8_context_snapshot.bin -o -name '*.so' -o -name '*.so.*' \
		-o -name '*.node' \) -print -quit | grep -q .
	# Exactly two payload files: the application archive and the helper we built.
	test "$$(find $(APPDIR) -type f | wc -l)" = 2
	# The helper must be our build, dynamically linked against the distribution's
	# C library, and must not have picked up a private Wayland client library.
	file -b $(APPDIR)/wayland-idle-helper | grep -q 'ELF 64-bit LSB pie executable'
	! objdump -p $(APPDIR)/wayland-idle-helper | grep -q 'NEEDED.*libwayland'

override_dh_auto_clean:
	rm -rf $(HELPER)/target debian/cargo-home

override_dh_auto_test:
	# Runtime behavior is covered by test/test-shared-electron-super-productivity.sh.
