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


BASEVERSION :=		$(shell make -s kernelversion)
KERNELVERSION :=	$(BASEVERSION)-rt

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)

# todo make flexible
KRN_ARCH = x86_64

%:
	dh $@

override_dh_auto_clean:
	# do not do this

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

override_dh_auto_install: $(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

$(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 $@

override_dh_strip:
	# not a good idea for the kernel

