#!/usr/bin/make -f
include /usr/share/dpkg/default.mk
# 1. Global Exports
export DEB_BUILD_MAINT_OPTIONS = hardening=+all
export DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)

# ADD THIS LINE: Point pkg-config to the directory containing wk2gtkpdf.pc
export PKG_CONFIG_PATH := $(CURDIR)/src/wk2gtkpdf:$(PKG_CONFIG_PATH)

# 2. Dynamic Version Detection
PODOFO_VERSION := $(shell pkg-config --modversion libpodofo 2>/dev/null || echo 0)
IS_010 := $(shell echo "$(PODOFO_VERSION)" | grep -q '^0.10' && echo yes || echo no)

ifeq ($(IS_010),yes)
    export DEB_CXXFLAGS_MAINT_APPEND = -DPODOFO_010
endif

# 3. Main Boilerplate
%:
	dh $@ --buildsystem=makefile

# 4. Custom Logic
override_dh_makeshlibs:
	dh_makeshlibs -V

override_dh_auto_build:
	# 1. Build the library first
	$(MAKE) -C src/wk2gtkpdf
	# 2. Build the CLI (Variable and command MUST be on the same execution line)
	LD_LIBRARY_PATH=$(CURDIR)/src/wk2gtkpdf $(MAKE) -C src/cli \
		USER_INCDIR="-I$(CURDIR)/src" \
		USER_LIBDIR="-L$(CURDIR)/src/wk2gtkpdf"

override_dh_auto_install:
	# Pass LIBDIR so files go to /usr/lib/x86_64-linux-gnu/ (or similar)
	$(MAKE) -C src/wk2gtkpdf install \
		DESTDIR=$(CURDIR)/debian/tmp \
		LIBDIR=/usr/lib/$(DEB_HOST_MULTIARCH)
	$(MAKE) -C src/cli install \
		DESTDIR=$(CURDIR)/debian/tmp

override_dh_install:
	# Sort files into packages based on your .install files
	dh_install
	# Force the manual into the CLI package
	dh_installman -pwkgtk-html2pdf debian/wkgtk-html2pdf.1
	# Install the Polkit rule into the library package specifically
	install -Dm 644 debian/50-wk2gtkpdf.rules \
		debian/libwk2gtkpdf0/usr/share/polkit-1/rules.d/50-wk2gtkpdf.rules

override_dh_installsystemd:
	# Tell debhelper that xvfb.service belongs to the library package
	dh_installsystemd -plibwk2gtkpdf0 --name=xvfb

override_dh_shlibdeps:
	# Clear those 85+ symbol warnings by pointing to the library we just built
	dh_shlibdeps -l$(CURDIR)/debian/libwk2gtkpdf0/usr/lib/$(DEB_HOST_MULTIARCH)
