#!/usr/bin/make -f

# This uses the debhelper sequencing helper
export DH_VERBOSE = 1

space			:= $(subst ,, )
DEB_VERSION		:= $(shell dpkg-parsechangelog --show-field Version)
DEB_VERSION_UPSTREAM	?= $(firstword $(subst ~,$(space),$(DEB_VERSION)))
DEB_REVISION		?= $(lastword $(subst -,$(space),$(DEB_VERSION)))
local_version		?= -rpi-$(DEB_REVISION)
abi_release		:= $(DEB_VERSION_UPSTREAM)$(local_version)

kmake=make ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu-
DESTDIR=$(CURDIR)/debian/tmp

%:
	dh $@

override_dh_auto_clean:
	# Standard kernel clean targets
	rm -rf debian/linux-rpi debian/tmp
	$(kmake) clean

override_dh_auto_configure:
	# Fix the kernel version string in the build config
	sed -i 's/.*CONFIG_LOCALVERSION=.*/CONFIG_LOCALVERSION="$(local_version)"/' arch/arm64/configs/bcm2711_defconfig
	# Enable RPi's BT by setting maximum number of UARTs as 1
	sed -i 's/.*CONFIG_SERIAL_8250_RUNTIME_UARTS=.*/CONFIG_SERIAL_8250_RUNTIME_UARTS=1/' arch/arm64/configs/bcm2711_defconfig
	# Enable loading archived in ZSTD firmware files
	echo "CONFIG_FW_LOADER_COMPRESS=y" >> arch/arm64/configs/bcm2711_defconfig
	echo "CONFIG_FW_LOADER_COMPRESS_ZSTD=y" >> arch/arm64/configs/bcm2711_defconfig
	$(kmake) bcm2711_defconfig

override_dh_auto_build:
	$(kmake) -j4 Image.gz modules dtbs

override_dh_auto_install:
	$(kmake) zinstall modules_install dtbs_install \
		INSTALL_PATH=$(DESTDIR)/boot \
		INSTALL_MOD_PATH=$(DESTDIR)/usr \
		INSTALL_DTBS_PATH=$(DESTDIR)/usr/lib/firmware/$(abi_release)/device-tree

	# Remove useless files
	rm $(DESTDIR)/usr/lib/modules/$(abi_release)/build
