#!/usr/bin/make -f
MODPKGBASE=bcm-linux-bde-modules

MAKE_SDK   = $(MAKE) -f debian/Makefile.sdk SDK=$(CURDIR)
PREFIX     = /usr
DESTDIR    = debian/tmp

include /usr/share/dpkg/default.mk

DEB_KFLAVOR=amd64-vyatta
DEB_KSUBARCH=none

ifeq (,$(KVERS))
KVERS := $(shell LIST=$$(ls /lib/modules/); for dir in $$LIST; do test -d /lib/modules/$$dir/build && echo $$dir; done | sort -V | head -1)
endif
KVERS_BINARY := $(shell dpkg-query -W -f='$${Version}\n' linux-headers-$(KVERS))
KVERS_DEPEND := linux-image-$(KVERS) (= $(KVERS_BINARY)) | linux-image-$(KVERS)-signed (= $(KVERS_BINARY)) | linux-image-$(KVERS)-unsigned (= $(KVERS_BINARY))
export KVER=$(KVERS)

export MODPKG=$(MODPKGBASE)-$(KVER)

# do parallel build
ifneq (,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
        NUMJOBS = $(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
        MAKEFLAGS += -j$(NUMJOBS)
endif

build: debian/control.modules
ifeq ($(filter noobs,$(DEB_BUILD_PROFILES)),)
	dh $@ --with signobs
else
	dh $@
endif

%:
ifeq ($(filter noobs,$(DEB_BUILD_PROFILES)),)
	dh $@ --with signobs
else
	dh $@
endif

debian/control.modules: debian/control.modules.in
	@if [ x"$(KVERS)" = x ] ; then \
		echo 'No kernel headers version found' >&2; \
		exit 1; \
	fi
	sed -e "s/_KVERS_/$(KVERS)/" -e "s/@KVERS_DEPEND@/$(KVERS_DEPEND)/"< $< > $@
	sed -i "/Package: $(MODPKGBASE)/d" debian/control
	sed -i '/Architecture: any/d' debian/control
	cat $@ >> debian/control

override_dh_auto_build:
	$(MAKE_SDK)

override_dh_auto_install:
	$(MAKE_SDK) install

override_dh_auto_clean:
	dh_auto_clean $@
	$(MAKE_SDK) clean
	rm -fr debian/control.modules
	sed -i "/Package: $(MODPKGBASE)-/,/`tail -n1 debian/control.modules.in`/d" debian/control
	if ! grep -qs "Package: $(MODPKGBASE)" debian/control; then \
		echo "Package: $(MODPKGBASE)" >> debian/control; \
		echo 'Architecture: any' >> debian/control; \
	fi
