#!/usr/bin/make -f
# Built against the kernel's headers package (linux-headers-<release>, a build dependency)
KREL := $(shell cat debian/kernel-release)
KOBJ ?= /lib/modules/$(KREL)/build
P := debian/ps3rsx-modules-$(KREL)
KMAKE := $(MAKE) -C $(KOBJ)
DEB_VERSION := $(shell dpkg-parsechangelog -S Version)
# The test switches, only where asked for. The recovery's wedge generator (test_allow_rt_enable_12)
# goes into the debug kernel's module; the VRAM clear's off switches (test_clear_off, test_reuse_off, test_gart_wait_off) into a build run
# with DEB_BUILD_OPTIONS=ps3rsx-testclear, whose version must also say testclear (a ~dev test build:
# tools/prebuilt-upload.sh refuses ~dev). Both reach Kbuild on its command line, set or empty, so a
# variable of the same name in the build environment can't turn them on. After the build, each
# parameter is in the module exactly when it was asked for, or the build fails.
TEST_WEDGE := $(if $(findstring -debug,$(KREL)),y)
TEST_CLEAR := $(if $(filter ps3rsx-testclear,$(DEB_BUILD_OPTIONS)),y)
ifneq ($(if $(findstring testclear,$(DEB_VERSION)),y),$(TEST_CLEAR))
$(error the version ($(DEB_VERSION)) and DEB_BUILD_OPTIONS disagree about ps3rsx-testclear)
endif
# has_parm KO NAME: is NAME one of the module's parameters? (its .modinfo strings)
has_parm = grep -aq 'parm=$(2):' $(1)

%:
	dh $@

override_dh_auto_build:
	mkdir -p b/ps3rsx b/probes
	cp src/* b/ps3rsx/
	cp probes/* b/probes/
	$(KMAKE) M=$(CURDIR)/b/ps3rsx PS3RSX_TEST_WEDGE=$(TEST_WEDGE) PS3RSX_TEST_CLEAR=$(TEST_CLEAR) modules
	if $(call has_parm,b/ps3rsx/ps3rsx.ko,test_clear_off); then [ "$(TEST_CLEAR)" = y ]; \
		else [ "$(TEST_CLEAR)" != y ]; fi || \
		{ echo "!! test_clear_off in the module: $(if $(TEST_CLEAR),missing,not asked for)"; exit 1; }
	if $(call has_parm,b/ps3rsx/ps3rsx.ko,test_reuse_off); then [ "$(TEST_CLEAR)" = y ]; \
		else [ "$(TEST_CLEAR)" != y ]; fi || \
		{ echo "!! test_reuse_off in the module: $(if $(TEST_CLEAR),missing,not asked for)"; exit 1; }
	if $(call has_parm,b/ps3rsx/ps3rsx.ko,test_gart_wait_off); then [ "$(TEST_CLEAR)" = y ]; \
		else [ "$(TEST_CLEAR)" != y ]; fi || \
		{ echo "!! test_gart_wait_off in the module: $(if $(TEST_CLEAR),missing,not asked for)"; exit 1; }
	if $(call has_parm,b/ps3rsx/ps3rsx.ko,test_allow_rt_enable_12); then [ "$(TEST_WEDGE)" = y ]; \
		else [ "$(TEST_WEDGE)" != y ]; fi || \
		{ echo "!! test_allow_rt_enable_12 in the module: $(if $(TEST_WEDGE),missing,not asked for)"; exit 1; }
	$(KMAKE) M=$(CURDIR)/b/probes modules

override_dh_auto_install:
	install -D -m 644 b/ps3rsx/ps3rsx.ko $(P)/lib/modules/$(KREL)/updates/ps3rsx.ko
	install -d $(P)/lib/modules/$(KREL)/extra
	install -m 644 b/probes/*.ko $(P)/lib/modules/$(KREL)/extra/
	install -d $(P)/usr/lib/modules-load.d
	echo ps3rsx > $(P)/usr/lib/modules-load.d/ps3rsx-$(KREL).conf

override_dh_auto_clean:
	rm -rf b
