#!/usr/bin/make -f
# export DH_VERBOSE = 1

export DEB_BUILD_MAINT_OPTIONS = hardening=+all
DPKG_EXPORT_BUILDFLAGS = 1
include /usr/share/dpkg/buildflags.mk
include /usr/share/dpkg/pkg-info.mk
export KBUILD_BUILD_TIMESTAMP = "@$(SOURCE_DATE_EPOCH)"

CONFOPTS += -Diqn_prefix=iqn.1993-08.org.debian:01
CONFOPTS += -Drulesdir=/usr/lib/udev/rules.d/

UDEB := $(filter open-iscsi-udeb,$(shell dh_listpackages))

%:
	dh $@ --buildsystem=meson

execute_before_dh_clean:
	rm -rf debian/build-deb
	rm -rf debian/build-udeb
	rm -rf debian/tmp-udeb

override_dh_auto_configure:
	dh_auto_configure --builddirectory=debian/build-deb  -- $(CONFOPTS)
ifneq ($(UDEB),)
	dh_auto_configure --builddirectory=debian/build-udeb -- $(CONFOPTS) -Dno_systemd=true
endif

override_dh_auto_build:
	dh_auto_build --builddirectory=debian/build-deb
ifneq ($(UDEB),)
	dh_auto_build --builddirectory=debian/build-udeb
endif

override_dh_auto_test:

override_dh_auto_install:
	dh_auto_install --builddirectory=debian/build-deb
ifneq ($(UDEB),)
	dh_auto_install --builddirectory=debian/build-udeb --destdir=$(CURDIR)/debian/tmp-udeb
endif

ifneq ($(UDEB),)
execute_after_dh_install:
	if strings debian/open-iscsi-udeb/usr/sbin/iscsid | grep libsystemd.so ; then \
		echo ERROR: udeb linked to libsystemd ;\
		exit 1 ;\
	fi
endif

override_dh_installinit:
	dh_installinit -p open-iscsi --no-start --no-enable --no-stop-on-upgrade --name=iscsid
	dh_installinit -p open-iscsi --no-start --no-enable --no-stop-on-upgrade
	dh_installinit -p iscsiuio --no-start --no-enable --no-stop-on-upgrade

override_dh_installsystemd:
	dh_installsystemd -p open-iscsi --no-restart-on-upgrade iscsid.socket
	dh_installsystemd -p open-iscsi --no-restart-on-upgrade open-iscsi.service
	dh_installsystemd -p iscsiuio --no-restart-on-upgrade iscsiuio.socket
	dh_installsystemd -p iscsiuio --no-restart-on-upgrade iscsiuio.service

override_dh_installdocs:
	dh_installdocs -p open-iscsi README sysfs-documentation THANKS
	dh_installdocs -p iscsiuio iscsiuio/RELEASE.TXT iscsiuio/README
	dh_installdocs -p libopeniscsiusr
	dh_installdocs -p libopeniscsiusr-dev

override_dh_makeshlibs:
ifneq ($(UDEB),)
	dh_makeshlibs --add-udeb=open-iscsi-udeb
else
	dh_makeshlibs
endif

# The following is taken from the initramfs-tools package. (We recommend
# busybox in the initramfs because otherwise we don't have access to the
# ip utility to set the default gateway after iscsistart -N is done.)
# On Debian we can use either busybox or busybox-static, but on Ubuntu
# and derivatives only busybox-initramfs will work.
BUSYBOX_PACKAGES := $(shell if dpkg-vendor --derives-from ubuntu; then echo busybox-initramfs; else echo busybox busybox-static; fi)

override_dh_gencontrol:
	echo >> debian/open-iscsi.substvars "busybox:Recommends=$(wordlist 2,100,$(BUSYBOX_PACKAGES:%=| %))"
	dh_gencontrol
