#!/usr/bin/make -f

# Disable tests which are not working
# for cross builds at the moment
# Although we override dh_auto_test we
# set this ENV to silence some warnings
export DEB_BUILD_OPTIONS=nocheck

#export DH_VERBOSE=1
export LDFLAGS=

# Set path to kernel headers
# Uncomment following line to compile against header package
# instead of kernel source tree
#export KERNELDIR=/usr/src/linux-headers-balluff-am67a-6.12-ti/

# Get path to kernel source tree
export KERNELDIR=$(shell find /usr/src/ -type d -name 'linux-balluff-am67a-6.12-ti*')

UPSTREAM_VERSION:=$(shell dpkg-parsechangelog --show-field Version | cut -d"-" -f 1)

# Construct the resulting build directory where the
# compiled kernel module is located.
BUILD_DIR:=$(PWD)/src/
DEBIAN_DIR:=$(PWD)/debian/

# Get the kernel version via kernelrelease target
KERNELVERSION:=$(shell ARCH=arm64 $(MAKE) --no-print-directory -C $(KERNELDIR) kernelrelease)

override_dh_auto_clean:
	ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- $(MAKE) -C $(KERNELDIR) M=$(BUILD_DIR) clean

# Copy Kbuild file to build directory before compiling
# to workaround unsuitable upstream Makefile
override_dh_auto_build:
	cp $(DEBIAN_DIR)/Kbuild $(BUILD_DIR)
	ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- $(MAKE) -C $(KERNELDIR) M=$(BUILD_DIR) -j $(shell nproc) modules

# Package contains only the kernel modules which is directly copied
# to the correct location by using override_dh_auto_install
# and depmod and ldconfig are called in postinst.
override_dh_auto_install:
	dh_install --sourcedir=$(BUILD_DIR) r8126.ko /lib/modules/$(KERNELVERSION)/extra
	dh_install --sourcedir=$(DEBIAN_DIR) r8126.conf /usr/lib/modprobe.d/

# Override the default dh_builddeb target to use xz compression (otherwise when using Ubuntu for packaging .zst will be used which isn't supported in bullseye)
override_dh_builddeb:
	dh_builddeb -- -Zxz

%:
	dh $@
