#!/usr/bin/make -f
# -*- makefile -*-
#export DH_VERBOSE=1

include /usr/share/dpkg/buildflags.mk
include /usr/share/dpkg/pkg-info.mk

#include /usr/share/cdbs/1/rules/debhelper.mk
#include /usr/share/cdbs/1/class/makefile.mk

#DEB_MAKE_INSTALL_TARGET = -f debian/rules custom_install

BASEVERSION :=		$(shell make -s kernelversion)
LOCALVERSIONRT :=	$(shell cat localversion-rt)
KERNELVERSION :=	$(BASEVERSION)$(LOCALVERSIONRT)
# todo make flexible
KRN_ARCH = x86_64

clean:
	dh_clean

build:	$(CURDIR)/.config
	@echo "Kernel version $(KERNELVERSION)"
	$(MAKE) -C .

build-arch: build

build-indep:

binary:
	dh_testroot
	dh_prep
	dh_installdirs
	$(MAKE) -f debian/rules custom_install
	dh_installdeb
	dh_gencontrol
	dh_md5sums
	dh_builddeb

binary-arch: binary

binary-indep: binary

$(CURDIR)/.config:
	@echo "remaking config"
	cp debian/config-$(KERNELVERSION).$(KRN_ARCH) $(CURDIR)/.config
	$(MAKE) -C . oldconfig

$(CURDIR)/debian/linux-image-preempt.postinst: $(CURDIR)/debian/linux-image-preempt.postinst.in
	@echo "making postinst script"
	sed -e "s/__KERNEL_VERSION__/$(KERNELVERSION)/" $< > $@
	chmod +x $@

# for the version, this relies on CONFIG_LOCALVERSION being appropriately
# set, e.g., rt16
# the rpm builds use a localversion-rt file, and re-purpose CONFIG_LOCALVERSION
# to indicate the build no -- supposedly needed for suse set-ups

LOCATION_IMG = $(CURDIR)/debian/linux-image-preempt/boot
LOCATION_MOD = $(CURDIR)/debian/linux-modules-preempt/lib/modules
LOCATION_HDR = $(CURDIR)/debian/linux-headers-preempt/usr/src/linux-headers-$(KERNELVERSION)



# installs in the debian install dirs
custom_install: $(CURDIR)/.config $(CURDIR)/debian/linux-image-preempt.postinst
	$(MAKE) -C . modules_install INSTALL_MOD_STRIP=1 \
		INSTALL_MOD_PATH=$(CURDIR)/debian/linux-modules-preempt
	find $(CURDIR)/debian/linux-modules-preempt/lib/modules \
		-name "*.ko" -type f >modnames
	xargs --no-run-if-empty chmod u+x < modnames
	install -d $(LOCATION_IMG)
	install -m 644 arch/$(KRN_ARCH)/boot/bzImage \
		$(LOCATION_IMG)/vmlinuz-$(KERNELVERSION)
	install -m 644 System.map \
		$(LOCATION_IMG)/System.map-$(KERNELVERSION)
	install -m 444 .config \
		$(LOCATION_IMG)/config-$(KERNELVERSION)
	cat Module.symvers | gzip -9 \
		>$(LOCATION_IMG)/symvers-$(KERNELVERSION).gz
	rm -f $(LOCATION_MOD)/$(KERNELVERSION)/build
	rm -f $(LOCATION_MOD)/$(KERNELVERSION)/source
	ln -sf /usr/src/linux-headers-$(KERNELVERSION) \
		$(LOCATION_MOD)/$(KERNELVERSION)/build
	ln -sf build \
		$(LOCATION_MOD)/$(KERNELVERSION)/source
	install -d $(LOCATION_HDR)
	tar --exclude=debian --exclude="*.o" --exclude="*.ko" \
	    --exclude=vmlinux scripts/*.c --exclude="*.c" --exclude=".pc" \
	    --exclude="*.mod" -cvf - . | \
	    (cd $(LOCATION_HDR) && tar xf -)
	install -d $(CURDIR)/debian/linux-headers-preempt/usr/sbin
	install -m 755 $(CURDIR)/debian/dkms-allow-preempt \
	    $(CURDIR)/debian/linux-headers-preempt/usr/sbin/dkms-allow-preempt
