#!/usr/bin/make -f

# See debhelper(7) (uncomment to enable)
# output every command that modifies files on the build system.
#export DH_VERBOSE = 1

unexport CFLAGS
unexport LDFLAGS

# This is the debhelper compatability version to use.
export DH_COMPAT=10
export LC_ALL=C
export SHELL=/bin/bash -e

include debian/parallel.mk

stub=lkrg
release		= $(shell $(CURDIR)/debian/findk release)
#flavours	= $(shell $(CURDIR)/debian/findk flavours)
# hardened kernel has CONFIG_KPROBES disabled, so we skip
# flavour autodetection and hardcode generic only
flavours	= generic
deb_arch = $(shell dpkg-architecture -qDEB_TARGET_ARCH)

builddir	:= $(CURDIR)/debian/build

build-arch: $(addprefix build-modules-,$(flavours))
build_arch = $(shell dpkg-architecture -qDEB_TARGET_GNU_CPU)
binary: $(addprefix binary-modules-,$(flavours))

build-modules-%:
	@echo "Preparing $*..."
	install -d $(builddir)/build-$*
	@echo "Building $*..."
	make -C $(CURDIR)/lkrg $(conc_level) P_KVER=$(release)-$*
	strip --strip-debug lkrg/p_lkrg.ko
	cp lkrg/p_lkrg.ko $(builddir)/build-$*
	md5sum $(builddir)/build-$*/p_lkrg.ko
	make -C $(CURDIR)/lkrg clean P_KVER=$(release)-$* ARCH=$(build_arch)
	@touch $@

# Install the finished build
install-%: build-modules-%
	dh_testdir
	dh_testroot
	dh_prep -p$(stub)-$(release)-$*

	md5sum $(builddir)/build-$*/p_lkrg.ko

	for script in postinst postrm install; do \
		sed -e 's/@@KVER@@/$(release)-$*/g' \
			debian/control-scripts/$(stub).$$script > \
			debian/$(stub)-$(release)-$*.$$script;	\
	done;

	dh_install --sourcedir=$(builddir)/build-$* -p$(pkgimg)
	dh_installdeb -p$(pkgimg)

binary-modules-%: pkgimg = $(stub)-$(release)-$*
binary-modules-%: install-%
	dh_testdir
	dh_testroot

	dh_installchangelogs -p$(pkgimg)
	dh_installdocs -p$(pkgimg)
	dh_compress -p$(pkgimg)
	dh_fixperms -p$(pkgimg)
	dh_installdeb -p$(pkgimg)
	dh_gencontrol -p$(pkgimg)
	dh_md5sums -p$(pkgimg)
	dh_builddeb -p$(pkgimg)

# Debian Build System targets
build: build-arch

### autogenerate debian/control
control:
	$(SHELL) debian/control-generate $(deb_arch) $(release) "$(flavours)"

.PHONY: control

clean-scripts-%:
	for script in postinst postrm install; do \
		rm -f debian/$(stub)-$(release)-$*.$$script;	\
	done;

clean: $(addprefix clean-scripts-,$(flavours)) control
	dh_testdir
	dh_testroot
	dh_clean

	rm -rf $(builddir)
