#!/usr/bin/make -f
SHELL := sh -e

include debian/rules.defs

GENCONTROL = debian/bin/gencontrol.py

DEB_HOST_ARCH  := $(shell dpkg-architecture -qDEB_HOST_ARCH)
DEB_BUILD_ARCH := $(shell dpkg-architecture -qDEB_BUILD_ARCH)

__BINNMU := $(shell dpkg-parsechangelog -SVersion | sed -rne 's,.*\+b([0-9]+)$$,\1,p')

build: build-arch build-indep
build-arch:
build-indep:

$(BUILD_DIR):
	@[ -d $@ ] || mkdir $@

clean: debian/control
	dh_testdir
	rm -rf $(BUILD_DIR)
	dh_clean
	find debian -maxdepth 1 -type l -delete
	rm -rf debian/files
	rm -rf debian/linux-*rpi*-rpfv

binary-indep: debian/control $(BUILD_DIR)
	dh_testdir
	$(MAKE) -f debian/rules.gen binary-indep

binary-arch: debian/control $(BUILD_DIR)
	dh_testdir
	$(MAKE) -f debian/rules.gen binary-arch_$(DEB_HOST_ARCH)

binary:	binary-indep binary-arch

CONTROL_FILES += debian/changelog $(wildcard debian/templates/control.*) 
debian/control debian/rules.gen: $(GENCONTROL) $(CONTROL_FILES)
ifeq ($(wildcard debian/control.md5sum),)
	$(MAKE) -f debian/rules debian/control-real
else ifeq ($(__BINNMU),)
	md5sum --check debian/control.md5sum --status || \
		$(MAKE) -f debian/rules debian/control-real
else
	grep -v debian/changelog debian/control.md5sum | md5sum --check - --status || \
		$(MAKE) -f debian/rules debian/control-real
endif

debian/control-real: $(GENCONTROL) $(CONTROL_FILES)
	$(GENCONTROL) /usr/src/linux-4.9-support-$(KERNELVERSION)
	md5sum $^ > debian/control.md5sum
	@echo
	@echo This target is made to fail intentionally, to make sure
	@echo that it is NEVER run during the automated build. Please
	@echo ignore the following error, the debian/control file has
	@echo been generated SUCCESSFULLY.
	@echo
	exit 1

ifdef DEBIAN_KERNEL_BUILD_ANY
binary-arch: binary-arch-all
endif

binary-arch-all: debian/control $(BUILD_DIR)
	dh_testdir
	$(MAKE) -f debian/rules.gen binary-arch

maintainerclean: clean
	rm -f debian/control debian/control.md5sum debian/rules.gen debian/*.bug-presubj debian/*.lintian-overrides
# dh_clean won't deal with binary packages that no longer exist after
# removal of a flavour.
	rm -rf $(filter-out %.config %.postinst %.templates %.NEWS, $(wildcard debian/linux-*))

.PHONY: clean build binary-indep binary-arch binary
