#!/usr/bin/make -f
DEST=$(CURDIR)/debian/zettlr
LIB=$(DEST)/usr/lib/zettlr
NODEHUN=app.asar.unpacked/.webpack/main/native_modules/build/Release/Nodehun.node

%:
	dh $@

override_dh_auto_build:
	# Application resources are generated by the checksum-pinned outer build.

override_dh_auto_install:
	install -d $(LIB) $(DEST)/usr/bin
	# cp -a preserves the app-payload/pandoc symlink into Ubuntu's pandoc.
	cp -a app-payload/. $(LIB)/
	printf '%s\n' '#!/bin/sh' 'set -eu' 'unset ELECTRON_RUN_AS_NODE' 'exec /usr/lib/electron-runtime-43/electron /usr/lib/zettlr/app.asar "$$@"' > $(DEST)/usr/bin/zettlr
	chmod 0755 $(DEST)/usr/bin/zettlr
	install -D -m 0644 debian/zettlr.desktop $(DEST)/usr/share/applications/zettlr.desktop
	install -D -m 0644 app-payload/icon.png $(DEST)/usr/share/icons/hicolor/512x512/apps/zettlr.png
	rm -f $(LIB)/icon.png
	# Electron resolves unpacked modules from app.asar.unpacked beside app.asar.
	test -s $(LIB)/app.asar
	test -s $(LIB)/$(NODEHUN)
	# Nodehun is the one expected native object; nothing else may ship.
	test "$$(find $(LIB) -type f -name '*.node' | wc -l)" = 1
	# Ubuntu's Pandoc, reached through the path the transformed bundle looks in.
	# dh_link rewrites this to the policy-mandated relative form after this
	# target runs, so assert the resolved target rather than the link text.
	test -L $(LIB)/pandoc
	test "$$(readlink -m $(LIB)/pandoc)" = /usr/bin/pandoc
	# APT owns updates: the release poller is gone and the default is off.
	grep -aq 'join("/usr/lib/zettlr",m);if(o.existsSync(g))' $(LIB)/app.asar
	grep -aq 'APT is the only update authority' $(LIB)/app.asar
	! grep -aq 'this._config.get().system.checkForUpdates&&this.check()' $(LIB)/app.asar
	! grep -aq 'checkForUpdates:!0' $(LIB)/app.asar
	# No private Electron/Chromium runtime and no bundled helper binary.
	! find $(LIB) -type f \( -name electron -o -name pandoc -o -name chrome-sandbox \
	    -o -name chrome_crashpad_handler -o -name resources.pak -o -name icudtl.dat \
	    -o -name '*.so' -o -name '*.so.*' -o -name '*.pak' -o -name '*.bin' \) -print -quit | grep -q .
	! find $(LIB) -type f -name '*.node' -not -path '*/native_modules/build/Release/Nodehun.node' -print -quit | grep -q .

override_dh_auto_test:
	# Runtime behaviour is covered by test/test-shared-electron-zettlr.sh.

override_dh_strip_nondeterminism:
	# The ASAR is a checksum-pinned application archive; do not rewrite it.
