#!/usr/bin/make -f

ifeq ($(shell dpkg-architecture -qDEB_HOST_ARCH),i386)
	skip_packages = -Nmultipath-tools
endif

# For Hardening
export DEB_BUILD_MAINT_OPTIONS = hardening=+all
export DEB_LDFLAGS_MAINT_STRIP=-Wl,-Bsymbolic-functions
DPKG_EXPORT_BUILDFLAGS = 1
include /usr/share/dpkg/buildflags.mk
include /usr/share/dpkg/pkg-info.mk

# Reproducible timestamp
export KBUILD_BUILD_TIMESTAMP = "@$(SOURCE_DATE_EPOCH)"

# Disable libdmmp, no known users exist
export ENABLE_LIBDMMP=0

TREENAMES = build-deb build-udeb

%:
	dh $@

execute_before_dh_clean:
	for treename in $(TREENAMES); do \
		rm -rf debian/$$treename ;\
	done
	# Force recreation of docs re. reproducibility
	rm -fv libdmmp/docs/man/dmmp_strerror.3

execute_before_dh_auto_configure:
	# no out of tree build support, prepare two source trees
	for treename in $(TREENAMES); do \
		mkdir debian/$$treename ;\
		cp -r -t debian/$$treename $$(find . -mindepth 1 -maxdepth 1 \! -name debian \! -name .git) ;\
	done

override_dh_auto_configure:

override_dh_auto_build:
	dh_auto_build --sourcedirectory=debian/build-deb
	# multipath-udeb: build separately; don't reference dynamic libgcc at runtime (#779579); disable systemd
	dh_auto_build --sourcedirectory=debian/build-udeb -- \
		SYSTEMD= EXTRACFLAGS="-static-libgcc"

override_dh_auto_test:

override_dh_auto_install:
	dh_auto_install --sourcedirectory=debian/build-deb -- DESTDIR=$(CURDIR)/debian/tmp/deb
	dh_auto_install --sourcedirectory=debian/build-udeb -- DESTDIR=$(CURDIR)/debian/tmp/udeb

	mkdir -p $(CURDIR)/debian/tmp/deb/etc
	cp debian/multipath.conf $(CURDIR)/debian/tmp/deb/etc

	# udebs dont get manpages
	rm -rf $(CURDIR)/debian/tmp/udeb/usr/share/man

	# Delete development files to prevent accidential linking of libraries with unlikely-to-be-stable ABI.
	rm \
		$(CURDIR)/debian/tmp/deb/usr/include/mpath_cmd.h \
		$(CURDIR)/debian/tmp/deb/usr/include/mpath_persist.h \
		$(CURDIR)/debian/tmp/udeb/usr/include/mpath_cmd.h \
		$(CURDIR)/debian/tmp/udeb/usr/include/mpath_persist.h \
		$(CURDIR)/debian/tmp/deb/usr/share/man/man3/mpath_persistent* \
		$(CURDIR)/debian/tmp/deb/usr/lib/libm*.so \
		$(CURDIR)/debian/tmp/udeb/usr/lib/libm*.so

execute_after_dh_install:
	if strings debian/multipath-udeb/usr/lib/libmultipath.so.0 | grep libsystemd.so ; then \
		echo ERROR: udeb linked to libsystemd ;\
		exit 1 ;\
	fi

override_dh_bugfiles:
	dh_bugfiles -A -pmultipath-tools -pmultipath-tools-boot

override_dh_installsystemd:
	dh_installsystemd -pmultipath-tools multipathd.service \
		--no-stop-on-upgrade

override_dh_makeshlibs:
	dh_makeshlibs -a --add-udeb=multipath-udeb

override_dh_builddeb:
	dh_builddeb ${skip_packages}

override_dh_gencontrol:
	dh_gencontrol ${skip_packages}

