#!/usr/bin/make -f

# Output every command that modifies files on the build system.
# Uncomment for debugging.
# export DH_VERBOSE = 1

# Get architecture-specific variables
DEB_HOST_MULTIARCH := $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)
DEB_BUILD_ARCH := $(shell dpkg-architecture -qDEB_BUILD_ARCH)

# Main target
%:
	dh $@ --parallel --buildsystem=cmake

# Override configure step to use an out-of-source build directory
override_dh_auto_configure:
	mkdir -p $(CURDIR)/obj-$(DEB_BUILD_ARCH)
	cd $(CURDIR)/obj-$(DEB_BUILD_ARCH) && \
	cmake -DCMAKE_INSTALL_PREFIX=/usr \
	      -DCMAKE_BUILD_TYPE=Release \
	      -DCMAKE_VERBOSE_MAKEFILE=ON \
	      -DCMAKE_INSTALL_LIBDIR=lib/$(DEB_HOST_MULTIARCH) \
	      -DCMAKE_FIND_ROOT_PATH=/usr/$(DEB_HOST_MULTIARCH) \
	      $(CURDIR)

# Override build step to ensure it uses the correct build directory
override_dh_auto_build:
	cd $(CURDIR)/obj-$(DEB_BUILD_ARCH) && $(MAKE) -j$(shell nproc)

# Override test step to handle missing tests gracefully
override_dh_auto_test:
	@if [ -f $(CURDIR)/obj-$(DEB_BUILD_ARCH)/CTestTestfile.cmake ]; then \
		cd $(CURDIR)/obj-$(DEB_BUILD_ARCH) && $(MAKE) test ARGS+=--verbose; \
	else \
		echo "No tests defined, skipping test phase."; \
	fi || true

# Override install step to ensure files are installed to debian/tmp
override_dh_auto_install:
	cd $(CURDIR)/obj-$(DEB_BUILD_ARCH) && \
	$(MAKE) install DESTDIR=$(CURDIR)/debian/tmp
