#!/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=$(shell dpkg-parsechangelog -SSource)

variants	= $(shell $(CURDIR)/debian/control-generate variants)
deb_arch = $(shell dpkg-architecture -qDEB_TARGET_ARCH)

builddir	:= $(CURDIR)/debian/build

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

build-modules-%:
	@echo "Preparing $*..."
	install -d $(builddir)/build-$*
	@echo "Building $*..."
	debian/special build "$(CURDIR)" "$(conc_level)" "$(build_arch)" "$*"
	find $(CURDIR) -name \*.ko -not -path '$(CURDIR)/debian/*' -print | while read f; do \
		strip --strip-debug "$$f"; \
		cp "$$f" $(builddir)/build-$*; \
		md5sum "$(builddir)/build-$*/$$(basename $$f)"; \
	done
	debian/special clean"$(CURDIR)" "$(conc_level)" "$(build_arch)" "$*"
	@touch $@

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

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

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

binary-modules-%: pkgimg = $(stub)-$*
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) "$(variants)"

.PHONY: control

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

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

	rm -rf $(builddir)

meta-%:
	dh_testdir
	dh_testroot
	dh_installchangelogs -p$*
	dh_installdocs -p$*
	dh_compress -p$*
	dh_fixperms -p$*
	dh_installdeb -p$*
	dh_gencontrol -p$*
	dh_md5sums -p$*
	dh_builddeb -p$* --

metapackages = $(shell $(CURDIR)/debian/control-generate metapackages)
binary: $(addprefix meta-,$(metapackages))
