#!/usr/bin/make -f

export DEB_BUILD_MAINT_OPTIONS = hardening=+all
include /usr/share/dpkg/default.mk

# Keep all fetch/build state inside the source tree so it is ignored by
# tar-ignore and removable by dh_auto_clean.
export YARN_CACHE_FOLDER := $(CURDIR)/debian/yarn-cache
export npm_config_cache := $(CURDIR)/debian/npm-cache
export ELECTRON_CACHE := $(CURDIR)/debian/electron-cache
export npm_config_update_notifier := false
# sbuild builds run with a HOME that does not exist and cannot be created;
# electron's install.js (@electron/get cache) and yarn's global-folder probe
# both need a writable HOME. Point it at an in-tree directory.
export HOME := $(CURDIR)/debian/home
# No Playwright-managed browsers and no visual tests in a package build.
export PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD := 1

YARN := $(CURDIR)/debian/tools/node_modules/.bin/yarn

PKGDIR  := $(CURDIR)/debian/pulsar
ROOTDIR := $(PKGDIR)/usr/lib/pulsar
APPDIR  := $(ROOTDIR)/resources/app

# Arch tags used by prebuild-install / 7zip-bin for per-platform binaries.
ifeq ($(DEB_HOST_ARCH),amd64)
HOST_NODE_ARCH := x64
else ifeq ($(DEB_HOST_ARCH),arm64)
HOST_NODE_ARCH := arm64
else ifeq ($(DEB_HOST_ARCH),armhf)
HOST_NODE_ARCH := arm
endif

# Electron's own Chromium locale packs. Pulsar's own translations live in
# the application ``locales`` directory and are shipped in full.
ELECTRON_LOCALES ?= en-US

%:
	dh $@

override_dh_auto_clean:
	dh_clean
	rm -rf $(CURDIR)/node_modules $(CURDIR)/ppm/node_modules \
	       $(CURDIR)/ppm/bin/node $(CURDIR)/apm-node-* \
	       $(CURDIR)/debian/tools $(CURDIR)/debian/yarn-cache \
	       $(CURDIR)/debian/npm-cache $(CURDIR)/debian/electron-cache \
	       $(CURDIR)/debian/home

override_dh_auto_build:
	# Pulsar pins a Yarn Classic (v1) lockfile; Debian's yarnpkg is Yarn 4,
	# which cannot read it. Bootstrap Yarn Classic into a private prefix,
	# the same way upstream CI does ("npm install -g yarn").
	mkdir -p $(CURDIR)/debian/tools
	npm install --prefix $(CURDIR)/debian/tools --no-audit --no-fund \
		--no-progress yarn@1.22.22
	# Install JS dependencies. The electron package's postinstall fetches
	# the pinned Electron 32.3.3 runtime into node_modules/electron/dist;
	# Parrot ships no electron package, so the runtime is fetched at build
	# time exactly as upstream pins it (checksum-verified by @electron/get).
	$(YARN) install --ignore-engines --frozen-lockfile
	# @parcel/watcher ships prebuilt N-API binaries as optional
	# dependencies; drop its binding.gyp so electron-rebuild never tries to
	# compile it from source, and drop the musl prebuilds which can never
	# load on a glibc system (mirrors upstream CI exactly).
	rm -f $(CURDIR)/node_modules/@parcel/watcher/binding.gyp
	rm -rf $(CURDIR)/node_modules/@parcel/watcher/build
	rm -rf $(CURDIR)/node_modules/@parcel/watcher-*-musl
	node -e "require('@parcel/watcher'); console.log('prebuilt @parcel/watcher loads')"
	# Rebuild the native modules (superstring, fuzzy-native, ctags,
	# git-utils, keytar, spellchecker, ...) against the Electron ABI.
	$(YARN) build
	# Build ppm (the bundled package manager). Its postinstall fetches the
	# pinned Node v20.18.1 into ppm/bin/node and rebuilds ppm's own native
	# dependencies with it. TMPDIR is pointed inside the tree because
	# download-node.js moves the unpacked runtime into ppm/bin and cannot
	# cross devices (upstream does the same in CI).
	cd $(CURDIR)/ppm && TMPDIR=$(CURDIR) $(YARN) install --ignore-engines --frozen-lockfile

# Everything binary here is prebuilt: the Electron runtime .so files
# already carry a .gnu_debuglink section (objcopy refuses a second one) and
# vendored helpers include foreign-arch ELFs (7zip-bin ships an arm 7za).
# Upstream strips its artifacts; nothing to gain from dh_strip here.
override_dh_strip:

# The packaged tree is a prebuilt vendor bundle: Electron's own .so files, a
# private git (dugite) built against /tmp/build/curl/lib and 7zip-bin shipping
# foreign-arch binaries for arm, arm64 and ia32 alongside ours. dpkg-shlibdeps
# cannot resolve any of that and must not be run over it; runtime libraries
# are declared in debian/control instead.
override_dh_makeshlibs:

override_dh_shlibdeps:

override_dh_auto_test:

override_dh_auto_install:
	# Mirror upstream's electron-builder deb layout, but under
	# /usr/lib/pulsar instead of /opt/Pulsar: the Electron runtime is
	# unpacked at the root, the application payload lives in
	# resources/app/, and pulsar.sh (installed in resources/) resolves the
	# install root relative to its own path.
	install -d $(APPDIR)
	# Electron runtime (binary is renamed `pulsar`, as upstream does).
	cp -a $(CURDIR)/node_modules/electron/dist/. $(ROOTDIR)/
	mv $(ROOTDIR)/electron $(ROOTDIR)/pulsar
	# Keep only the requested Chromium locale packs.
	set -e; for pak in $(ROOTDIR)/locales/*.pak; do \
		case " $(ELECTRON_LOCALES) " in \
			*" $$(basename $$pak .pak) "*) ;; \
			*) rm -f "$$pak" ;; \
		esac; \
	done
	# Prune development dependencies from the source tree before copying the
	# payload, the way upstream's electron-builder does (it installs the
	# production dependency tree only). Doing this by deleting top-level
	# devDependency *names* is wrong: a name can also be required at runtime
	# by a dependency (``random-seed`` is a devDependency here and a
	# runtime dependency of ``line-top-index``). ``--production`` keeps
	# everything the runtime tree needs and drops the rest.
	cd $(CURDIR) && $(YARN) install --production --ignore-scripts \
		--ignore-engines --frozen-lockfile --no-progress
	# ppm is shipped inside the app payload; its bin scripts and bundled
	# native modules stay, its build-only dependencies do not.
	cd $(CURDIR)/ppm && $(YARN) install --production --ignore-scripts \
		--ignore-engines --frozen-lockfile --no-progress
	# Application payload, matching upstream's electron-builder `files`
	# list.
	for item in package.json dot-atom exports resources src static vendor \
	            locales node_modules; do \
		cp -aL $(CURDIR)/$$item $(APPDIR)/; \
	done
	cp -aL $(CURDIR)/ppm $(APPDIR)/ppm
	rm -rf $(APPDIR)/node_modules/.bin $(APPDIR)/node_modules/.yarn-integrity \
	       $(APPDIR)/ppm/node_modules/.bin \
	       $(APPDIR)/ppm/node_modules/.yarn-integrity
	# Native modules ship up to three copies of each binary (build/Release,
	# build/Release/obj.target, and a prebuilt bin/ directory) plus the
	# sources they were compiled from. Upstream's electron-builder excludes
	# all of that; so do we.
	find $(APPDIR) -type d \( -name obj.target -o -name .deps \) \
		-prune -exec rm -rf {} +
	find $(APPDIR) -type d -path '*/build/Release/obj' -prune -exec rm -rf {} +
	find $(APPDIR) -type f \( -name '*.cc' -o -name '*.h' -o -name '*.js.map' \
		-o -name '*.d.ts' \) -delete
	find $(APPDIR)/node_modules -mindepth 2 -maxdepth 3 -type d \
		\( -name test -o -name tests -o -name __tests__ -o -name example \
		   -o -name examples -o -name docs -o -name .github \) \
		-prune -exec rm -rf {} +
	find $(APPDIR)/node_modules -type f -name '*.md' \
		! -iname 'license*' ! -iname 'copying*' -delete
	# Only the host architecture's prebuilt binaries can ever be loaded.
	rm -rf $(APPDIR)/node_modules/7zip-bin/win \
	       $(APPDIR)/node_modules/7zip-bin/mac
	for d in $(APPDIR)/node_modules/7zip-bin/linux/*; do \
		[ "$$(basename $$d)" = "$(HOST_NODE_ARCH)" ] || rm -rf "$$d"; \
	done
	set -e; for a in x64 arm64 arm ia32 armv7l; do \
		[ "$$a" = "$(HOST_NODE_ARCH)" ] && continue; \
		find $(APPDIR)/node_modules -type d \
			\( -path "*/bin/linux-$$a" -o -path "*/bin/linux-$$a-*" \
			   -o -path "*/prebuilds/linux-$$a" -o -path "*/prebuilds/linux-$$a-*" \) \
			-prune -exec rm -rf {} + ; \
	done
	# Windows and macOS resources cannot be used on Linux.
	rm -rf $(APPDIR)/resources/mac $(APPDIR)/resources/win
	# ppm ships its own Node runtime; use the distribution's nodejs instead.
	# Both are Node 20.x, so the ABI (and ppm's native modules) still match.
	rm -f $(APPDIR)/ppm/bin/node
	ln -s /usr/bin/node $(APPDIR)/ppm/bin/node
	# Hardlink identical files (prebuilds that match our rebuilds, duplicated
	# licence/asset files). dpkg stores hardlinks as hardlinks, so this costs
	# one copy on disk.
	find $(APPDIR) -type f ! -perm -u+x -size +8k -print0 \
		| xargs -0 -r md5sum | sort \
		| awk -F'  ' '$$1==prev{print $$2"\t"keep;next}{prev=$$1;keep=$$2}' \
		| while IFS=$$'\t' read -r dup keep; do \
			ln -f "$$keep" "$$dup" 2>/dev/null || true; \
		done
	# Launcher script and icon as extraResources (upstream copies these to
	# resources/ and the post-install script links them into /usr/bin).
	cp -a $(CURDIR)/pulsar.sh \
		$(CURDIR)/debian/pulsar/usr/lib/pulsar/resources/pulsar.sh
	cp -a $(CURDIR)/resources/app-icons/beta.png \
		$(CURDIR)/debian/pulsar/usr/lib/pulsar/resources/pulsar.png
	cp -a $(CURDIR)/LICENSE.md \
		$(CURDIR)/debian/pulsar/usr/lib/pulsar/resources/LICENSE.md
	# Command-line entry points.
	install -d $(CURDIR)/debian/pulsar/usr/bin
	dh_link usr/lib/pulsar/resources/pulsar.sh usr/bin/pulsar
	dh_link usr/lib/pulsar/resources/app/ppm/bin/ppm usr/bin/ppm
	# Desktop integration.
	install -d $(CURDIR)/debian/pulsar/usr/share/applications
	install -Dm644 debian/pulsar.desktop \
		$(CURDIR)/debian/pulsar/usr/share/applications/pulsar.desktop
	set -e; \
	for size in 16 22 24 32 48 64 128 256 384 512; do \
		if [ -f $(CURDIR)/resources/icons/$${size}x$${size}.png ]; then \
			install -Dm644 $(CURDIR)/resources/icons/$${size}x$${size}.png \
				$(CURDIR)/debian/pulsar/usr/share/icons/hicolor/$${size}x$${size}/apps/pulsar.png; \
		fi; \
	done
	install -Dm644 $(CURDIR)/resources/app-icons/beta.svg \
		$(CURDIR)/debian/pulsar/usr/share/icons/hicolor/scalable/apps/pulsar.svg
