#!/usr/bin/make -f

#~ export DEB_BUILD_MAINT_OPTIONS=nocheck
export DH_VERBOSE=1

include /usr/share/dpkg/architecture.mk
include /usr/share/dpkg/buildflags.mk

srctree ?= .
KERNEL_ARCH := x86
# Import some variables
include debian/rules.d/custom-config.mk

CHECK_DEBUG_PACKAGE := $(shell if grep -q -x "Package: linux-image-$(KERNELVER_REL)-dbg" debian/control; then echo true; else echo false; fi)

NUMCPUS := $(shell grep -c '^processor' /proc/cpuinfo)
PARALLEL_BUILD=-j$(NUMCPUS)

#~ KERNEL_MAKE := $(MAKE) KERNELRELEASE=$(KERNELVER_REL) ARCH=$(KERNEL_ARCH) KBUILD_BUILD_VERSION=$(KERNEL_BUILD_VERSION) -f Makefile
KERNEL_MAKE := $(MAKE) KERNELRELEASE=$(KERNELVER_REL) ARCH=x86  $(PARALLEL_BUILD) KBUILD_BUILD_VERSION=1 -f $(srctree)/Makefile


%:
	dh $@

override_dh_auto_configure:
	# Copy over the correct config file before building the kernel
	cp debian/config/$(CUSTOM_KERNEL_CONFIG)/$(SELECTED_BUILD).config .config

override_dh_auto_build:
	# Build the full kernel and all its configured options
	$(KERNEL_MAKE)

override_dh_auto_install:
	# Run the install script
	$(KERNEL_MAKE) intdeb-pkg

	# Copy over the maintainer scripts before removing the DEBIAN folder
	cp debian/tmp/DEBIAN/postinst debian/linux-image-$(KERNELVER_REL).postinst
	cp debian/tmp/DEBIAN/postrm debian/linux-image-$(KERNELVER_REL).postrm
	cp debian/tmp/DEBIAN/preinst debian/linux-image-$(KERNELVER_REL).preinst
	cp debian/tmp/DEBIAN/prerm debian/linux-image-$(KERNELVER_REL).prerm
	rm -rf debian/tmp/DEBIAN debian/hdrtmp/DEBIAN

	# Use dh_install to install from the staging directory
	dh_install -p linux-image-$(KERNELVER_REL) debian/tmp/* /
	dh_install -p linux-headers-$(KERNELVER_REL) debian/hdrtmp/* /
	dh_install -p linux-libc-dev debian/headertmp/* /
	
#~ 	# Check if the debug package entry should be built
#~ ifeq ($(CHECK_DEBUG_PACKAGE), true)
#~ 	dh_install -p linux-image-$(KERNELVER_REL)-dbg debian/linux-image-dbg/* /
#~ endif

override_dh_missing:
	dh_missing --list-missing

override_dh_strip:
	dh_strip --no-automatic-dbgsym 

override_dh_auto_clean:
	$(MAKE) clean
	rm -rf debian/files debian/linux-* debian/tmp
