#!/usr/bin/make -f

export GHOSTTY_VERSION = $(shell dpkg-parsechangelog -S Version | sed 's/-.*//')

%:
	dh $@

override_dh_auto_configure:
	# No configure step for zig builds.

override_dh_auto_build:
	# Debian names it libbz2, not libbzip2.
	sed -i 's/linkSystemLibrary2("bzip2", dynamic_link_opts)/linkSystemLibrary2("bz2", dynamic_link_opts)/' src/build/SharedDeps.zig

override_dh_auto_install:
	DESTDIR=$(CURDIR)/debian/ghostty \
	ZIG_GLOBAL_CACHE_DIR=$(CURDIR)/.zig-cache \
	zig build \
		--prefix /usr \
		--system $(CURDIR)/zigcache/p \
		-Doptimize=ReleaseFast \
		-Dcpu=baseline \
		-Dpie=true \
		-Dstrip=false \
		-Dversion-string=$(GHOSTTY_VERSION)
	# Strip RPATH from binary.
	chrpath -d $(CURDIR)/debian/ghostty/usr/bin/ghostty
	# Remove static libraries.
	find $(CURDIR)/debian/ghostty -name '*.a' -delete
	# Remove libghostty-vt dev files (not split into separate packages yet).
	rm -r $(CURDIR)/debian/ghostty/usr/include
	rm $(CURDIR)/debian/ghostty/usr/lib/libghostty-vt.so
	rm $(CURDIR)/debian/ghostty/usr/share/pkgconfig/libghostty-vt.pc
	rmdir --ignore-fail-on-non-empty $(CURDIR)/debian/ghostty/usr/share/pkgconfig 2>/dev/null || true
	# Fix KDE service menu desktop file permissions.
	chmod 0644 $(CURDIR)/debian/ghostty/usr/share/kio/servicemenus/*.desktop
	# terminfo: ship xterm-ghostty, remove ghostty (conflicts with ncurses-term).
	rm $(CURDIR)/debian/ghostty/usr/share/terminfo/g/ghostty
	rmdir --ignore-fail-on-non-empty $(CURDIR)/debian/ghostty/usr/share/terminfo/g 2>/dev/null || true
	# Remove HTML/Markdown man page copies (duplicates of proper man pages).
	rm -r $(CURDIR)/debian/ghostty/usr/share/ghostty/doc

override_dh_auto_test:
	ZIG_GLOBAL_CACHE_DIR=$(CURDIR)/.zig-cache \
	zig build test \
		--system $(CURDIR)/zigcache/p \
		-Dcpu=baseline

override_dh_auto_clean:
	rm -rf .zig-cache zig-out
