#!/usr/bin/make -f

export DEB_BUILD_MAINT_OPTIONS = hardening=+all
export DEB_LDFLAGS_MAINT_APPEND = -Wl,-O1 -Wl,-z,defs
export DPKG_GENSYMBOLS_CHECK_LEVEL = 4

# Filter out that flag for Ubuntu, it's default there but fails the build
# https://gitlab.gnome.org/GNOME/gcr/issues/43
export DEB_LDFLAGS_MAINT_STRIP = -Wl,-Bsymbolic-functions

ifneq ($(DEB_HOST_ARCH_OS),linux)
SYSTEMD = -Dsystemd=disabled
SSH_AGENT = -Dssh_agent=false -Dgtk4=false
endif

TESTS_BUILD_DIR=debian/build/installed-tests
TESTS_INSTALL_DIR=usr/libexec/installed-tests/gcr4
TESTS_PKG=gcr4-tests

%:
	dh $@

override_dh_auto_configure:
	dh_auto_configure -- \
		-Dauto_features=enabled \
		-Dgtk_doc=true \
		-Dintrospection=true \
		$(SSH_AGENT) \
		$(SYSTEMD)

	# Setup installed-tests with custom paths
	@echo "#define SRCDIR \"/$(TESTS_INSTALL_DIR)\"" >> debian/test-vars.h
	@echo "#define _GCK_TEST_MODULE_PATH \"/$(TESTS_INSTALL_DIR)/libmock-test-module.so\"" >> debian/test-vars.h
	@echo "#define _GCR_TEST_SSH_ASKPASS_PATH \"/usr/libexec/gcr4-ssh-askpass\"" >> debian/test-vars.h
	CFLAGS="$(CFLAGS) --include $(shell pwd)/debian/test-vars.h" dh_auto_configure \
		--builddirectory=$(TESTS_BUILD_DIR)

# Compile installed-tests
execute_after_dh_auto_build-arch:
	dh_auto_build \
		--builddirectory=$(TESTS_BUILD_DIR) \
		-- \
		meson-test-prereq

override_dh_auto_test:
	# Disable fakeroot as this confuses some of the tests
	env -u LD_PRELOAD dbus-run-session -- dh_auto_test

# Install tests
execute_after_dh_auto_install-arch:
	mkdir -p debian/tmp/$(TESTS_INSTALL_DIR)
	find $(TESTS_BUILD_DIR) -type f -executable \
		\( \
			-path "*/egg/egg-*" -o \
			-path "*/gck/test-*" -o \
			-path "*/gcr/test-*" \
		\) \
		-exec install -m 0755 {} debian/tmp/$(TESTS_INSTALL_DIR) \;
	install -m 0644 $(TESTS_BUILD_DIR)/gck/libgck-test*.so debian/tmp/$(TESTS_INSTALL_DIR)
	install -m 0644 $(TESTS_BUILD_DIR)/gck/libmock-test-module.so debian/tmp/$(TESTS_INSTALL_DIR)
	cp -r --parents egg/fixtures debian/tmp/$(TESTS_INSTALL_DIR)
	cp -r --parents gcr/fixtures debian/tmp/$(TESTS_INSTALL_DIR)

# debhelper >= 13.4 makes all of /usr/libexec executable, which is not
# quite right for installed-tests
override_dh_fixperms-arch:
	dh_fixperms -X$(TESTS_INSTALL_DIR)

	chmod -R a=r,u+w,a+X debian/$(TESTS_PKG)/$(TESTS_INSTALL_DIR)/*/fixtures/
	chmod +x debian/$(TESTS_PKG)/$(TESTS_INSTALL_DIR)/gcr/fixtures/gnupg-mock/*

execute_after_dh_clean:
	rm -rf debian/build
	rm -f  debian/test-vars.h

override_dh_gnome_clean:
