#!/usr/bin/make -f

%:
	dh $@ --with bash-completion

# 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)
BUSYBOX_MIN_VERSION := 1:1.22.0-17~

override_dh_gencontrol:
	echo >> debian/initramfs-tools-core.substvars "busybox:Breaks=$(wordlist 2,100,$(BUSYBOX_PACKAGES:%=, % (<< $(BUSYBOX_MIN_VERSION))))"
	echo >> debian/initramfs-tools-core.substvars "busybox:Depends=$(wordlist 2,100,$(BUSYBOX_PACKAGES:%=| % (>= $(BUSYBOX_MIN_VERSION))))"
	dh_gencontrol

override_dh_install:
	install -d debian/initramfs-tools-core/usr/sbin
	sed -e 's,@BUSYBOX_PACKAGES@,$(wordlist 2,100,$(BUSYBOX_PACKAGES:%=or %)),' \
	    -e 's/@BUSYBOX_MIN_VERSION@/$(BUSYBOX_MIN_VERSION)/' \
		mkinitramfs > debian/initramfs-tools-core/usr/sbin/mkinitramfs
	chmod 755 debian/initramfs-tools-core/usr/sbin/mkinitramfs
	dh_install
ifneq (,$(filter initramfs-tools,$(shell dh_listpackages)))
	install -d debian/initramfs-tools/usr/share/initramfs-tools/scripts/panic
	cp -a scripts/init-top/keymap \
		debian/initramfs-tools/usr/share/initramfs-tools/scripts/panic/keymap
	sed -i -e "/^OPTION=/d" \
		debian/initramfs-tools/usr/share/initramfs-tools/scripts/panic/keymap
endif

DEB_BUILD_GNU_TYPE := $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE)
DEB_HOST_GNU_TYPE  := $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE)
DEB_HOST_ARCH  := $(shell dpkg-architecture -qDEB_HOST_ARCH)
ifeq ($(DEB_BUILD_GNU_TYPE),$(DEB_HOST_GNU_TYPE))
CROSS :=
else
CROSS := CC=$(DEB_HOST_GNU_TYPE)-gcc PKG_CONFIG=$(DEB_HOST_GNU_TYPE)-pkg-config
endif

TEST_ARCHES="amd64 i386"
override_dh_auto_build:
	make -C src $(CROSS)
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
ifneq (,$(findstring $(DEB_HOST_ARCH),$(TEST_ARCHES)))
	./tests/run-tests
endif
endif

override_dh_auto_clean:
	make -C src clean
