#!/usr/bin/make -f
.ONESHELL:
SHELL := /bin/bash
.SHELLFLAGS := -e -o pipefail -c

# Include dpkg package info only after 'prepare' has generated debian/changelog.
# If the file still contains the @PKGVER@ placeholder, skip the include to
# avoid confusing dpkg-parsechangelog warnings.
ifneq ($(wildcard debian/changelog),)
ifeq ($(shell grep -qF '@PKGVER@' debian/changelog 2>/dev/null && echo template || echo ready),ready)
include /usr/share/dpkg/pkg-info.mk
export DEB_VERSION
endif
endif

export DH_VERBOSE ?= 1
export KBUILD_VERBOSE := 1
export ARCH = arm64

# Optional out-of-tree build directory (honor either O or KBUILD_OUTPUT).
BUILD_OBJ ?= $(or $(O),$(KBUILD_OUTPUT))

# Make argument that is empty when BUILD_OBJ is empty.
KBUILD_O_ARG := $(if $(BUILD_OBJ),O=$(BUILD_OBJ),)

# Parallel jobs (override with DEB_BUILD_OPTIONS=parallel=N if desired).
PARALLEL ?= $(shell nproc)

# objcopy for debug symbol extraction (cross-compile aware).
OBJCOPY ?= $(shell which aarch64-linux-gnu-objcopy 2>/dev/null || which objcopy 2>/dev/null || echo objcopy)

# readelf for reading module build IDs. It parses ELF directly and is not tied
# to a target, so the host one would do; resolved the same way as OBJCOPY above
# to match how the kernel's own scripts/package/builddeb picks its READELF.
READELF ?= $(shell which aarch64-linux-gnu-readelf 2>/dev/null || which readelf 2>/dev/null || echo readelf)

# dkms identifies architectures in uname -m vocabulary (aarch64), unlike the
# kbuild ARCH token above (arm64). The distinction matters for dkms.conf
# BUILD_EXCLUSIVE_ARCH gates, which match against this value.
DKMS_ARCH ?= aarch64

# File that caches the kernelrelease (uname -r) written by override_dh_auto_build.
KREL_FILE := debian/kernel.release

%:
	dh $@ --buildsystem=makefile

# ---------------------------------------------------------------------------
# prepare: generate debian/control and debian/changelog from *.in templates.
#
# Must be called before dpkg-buildpackage / sbuild since those tools read
# debian/control before invoking any debian/rules targets.
#
# Inputs (make variables):
#   LOCALVERSION   Suffix appended to the base kernel version, e.g. +qcom-next-20260722.
#                  Required unless KVER is given explicitly.
#   KVER           Full kernelrelease string (uname -r). Overrides LOCALVERSION.
#   KVER_EXTRA     Optional extra suffix appended after LOCALVERSION, e.g. -ci42.
#   SNAPSHOT       Dated component of the Debian version: YYYYMMDD with an
#                  optional .<respin> ordinal, e.g. 20260722 or 20260722.1.
#                  A build without one carries no +git<date> at all.
#   GITSHA         Commit the build was cut from, 12 hex characters. Appended to
#                  the snapshot as a final discriminator. Ignored without a
#                  SNAPSHOT to discriminate.
#   DISTRO         Target Debian/Ubuntu suite (default: unstable).
#   SRCPKG         Source package name (default: linux-qcom-next).
#   BINPKG         Binary metapackage name (default: linux-image-qcom-next).
#   DEBIAN_REVISION  Debian revision component of the package version (default: 0qcom1).
#   DKMS_MODULES     Comma-separated out-of-tree DKMS modules to build and ship,
#                    each named without the -dkms suffix (e.g.
#                    DKMS_MODULES=kgsl,camx). Empty (the default) builds
#                    nothing. Each name must have a <name>-dkms package available
#                    in the build environment; the Build-Depends entry for it is
#                    generated from this list, so nothing else declares it.
#                    Each entry produces its own binary packages, the versioned
#                    <name>-modules-<KVER> and <name>-modules-<KVER>-dbg plus
#                    the unversioned <BINPKG>-modules-<name> metapackage, whose
#                    control stanzas are generated from debian/control-dkms.in.
#                    A non-empty list also produces one <BINPKG>-modules
#                    metapackage depending on all of them, generated from
#                    debian/control-dkms-all.in.
#                    The modules are NOT installed into linux-image-<KVER>.
#   GIT_CLONE        Kernel repository URL, recorded in debian/changelog.
#   GIT_REF          Resolved kernel ref (tag or branch), recorded in the changelog.
#   GIT_SHA          Full kernel HEAD commit SHA, recorded in the changelog.
#                    GITSHA above is the same commit at 12 characters, for the
#                    version strings; this is the unabbreviated value.
#   CHANGELOG_DATE   Date of the changelog entry, RFC 2822 (date -R form).
#                    prepare-source.sh passes the kernel commit's committer
#                    date, so the entry is dated by the source it describes
#                    and two builds of one commit write one changelog.
#                    dpkg-source takes the debian tarball's mtimes from this
#                    date and dpkg-buildpackage exports it as
#                    SOURCE_DATE_EPOCH, so it is also what makes the source
#                    package reproducible. Defaults to now, for a prepare run
#                    by hand.
#
# Outputs (generated files, all listed in debian/clean):
#   debian/control       Substituted from debian/control.in, with one group of
#                        stanzas per DKMS_MODULES entry appended from
#                        debian/control-dkms.in, plus a single all-modules
#                        metapackage stanza from debian/control-dkms-all.in
#                        when the list is not empty
#   debian/changelog     Substituted from debian/changelog.in
#   debian/dkms-modules  Manifest of the DKMS_MODULES entries, read at build time
#                        by debian/scripts/bundle-dkms-modules.sh and by
#                        override_dh_gencontrol. Always written,
#                        so an empty DKMS_MODULES is a genuine "bundle nothing"
#                        rather than the missing-manifest misconfiguration that
#                        the bundler rejects.
#   debian/localversion  Plain file containing the LOCALVERSION suffix (e.g. +qcom-next-20260722).
#                        Read by override_dh_auto_build to pass LOCALVERSION= to make.
#   debian/pkgversion    Plain file containing the full Debian package version
#                        (e.g. 7.2.0~rc3+git20260722-0qcom1).
#                        Read by override_dh_gencontrol.
# ---------------------------------------------------------------------------
KVER_EXTRA       ?=
SNAPSHOT         ?=
GITSHA           ?=
DISTRO           ?= unstable
SRCPKG           ?= linux-qcom-next
BINPKG           ?= linux-image-qcom-next
DEBIAN_REVISION  ?= 0qcom1
DKMS_MODULES     ?=
# Source provenance recorded in debian/changelog. The version strings name the
# commit but not the repository it came from, so without these a build cannot be
# traced back to its source tree.
GIT_CLONE        ?= unknown
GIT_REF          ?= unknown
GIT_SHA          ?= unknown
CHANGELOG_DATE   ?= $(shell date -R)

.PHONY: prepare
prepare:
	@set -e; \
	\
	# ── Resolve KVER (uname -r) ──────────────────────────────────────────────
	if [ -n "$(KVER)" ]; then \
		KVER_RESOLVED="$(KVER)"; \
	else \
		[ -n "$(LOCALVERSION)" ] || { \
			echo "ERROR: LOCALVERSION is required when KVER is not set."; \
			echo "       Pass LOCALVERSION=<suffix> (e.g. LOCALVERSION=+qcom-next-20260722)"; \
			echo "       or KVER=<full-kernelrelease> (e.g. KVER=7.2.0-rc3+qcom-next-20260722)"; \
			exit 1; \
		}; \
		echo "Reading base kernel version from kernel Makefile..."; \
		VER=$$(grep '^VERSION = ' Makefile | awk '{print $$3}'); \
		PATCH=$$(grep '^PATCHLEVEL = ' Makefile | awk '{print $$3}'); \
		SUB=$$(grep '^SUBLEVEL = ' Makefile | awk '{print $$3}'); \
		EXTRA=$$(grep '^EXTRAVERSION = ' Makefile | awk '{print $$3}' || true); \
		TREE_LOCALVER=$$(cat localversion* 2>/dev/null | tr -d '\n' || true); \
		BASE_KVER="$${VER}.$${PATCH}.$${SUB}$${EXTRA}$${TREE_LOCALVER}"; \
		KVER_RESOLVED="$${BASE_KVER}$(LOCALVERSION)"; \
		echo "Resolved KVER=$$KVER_RESOLVED (base=$$BASE_KVER, LOCALVERSION=$(LOCALVERSION))"; \
	fi; \
	if [ -n "$(KVER_EXTRA)" ]; then \
		KVER_RESOLVED="$${KVER_RESOLVED}$(KVER_EXTRA)"; \
		echo "Appended KVER_EXTRA=$(KVER_EXTRA) -> KVER=$$KVER_RESOLVED"; \
	fi; \
	\
	# ── Derive package version ───────────────────────────────────────────────
	# Package version format: <base_kver>+git<snapshot>~g<sha>-<debian_revision>
	# where base_kver = kernel version without the LOCALVERSION suffix, and
	# snapshot = the SNAPSHOT input (YYYYMMDD with an optional respin ordinal).
	# Without a snapshot, version = <base_kver>-<debian_revision>.
	#
	# The snapshot orders these; the SHA only discriminates two builds that
	# share one. It is joined with '~' rather than '.' because dpkg alternates
	# digit and non-digit runs and reads an exhausted run as lower than a
	# letter, so a '.' would put a respin BELOW the build it respins:
	#
	#   7.2.0+git20260826.g3f2f3ca1a81e  >  7.2.0+git20260826.1.gabcdef123456
	#
	# '~' sorts below everything, including the empty string, so the ordinal is
	# always compared before the SHA is reached and no build has to spell a
	# ".0" to hold the position. The cost is that a version reads as preceding
	# the same snapshot without a SHA -- a slot nothing ever occupies, since
	# every snapshot build carries one.
	#
	# Extract base_kver: read directly from kernel Makefile (same as above but
	# without LOCALVERSION appended), so it is always the pure kernel version.
	VER=$$(grep '^VERSION = ' Makefile | awk '{print $$3}'); \
	PATCH=$$(grep '^PATCHLEVEL = ' Makefile | awk '{print $$3}'); \
	SUB=$$(grep '^SUBLEVEL = ' Makefile | awk '{print $$3}'); \
	EXTRA=$$(grep '^EXTRAVERSION = ' Makefile | awk '{print $$3}' || true); \
	TREE_LOCALVER=$$(cat localversion* 2>/dev/null | tr -d '\n' || true); \
	# Translate -rcN to ~rcN for the Debian version field only.
	# dpkg ordering: 7.2.0~rc3 < 7.2.0 (correct); 7.2.0-rc3 > 7.2.0 (wrong).
	# EXTRA (used for KVER_RESOLVED / uname -r) is left unchanged.
	EXTRA_DEB=$$(echo "$$EXTRA" | sed 's/^-rc/~rc/'); \
	BASE_KVER_CLEAN="$${VER}.$${PATCH}.$${SUB}$${EXTRA_DEB}$${TREE_LOCALVER}"; \
	\
	# SNAPSHOT arrives as its own input rather than being recovered from the end
	# of LOCALVERSION, because that string is not safely parseable: it carries a
	# variant name whose shape is caller-supplied, and a 12-hex SHA that can
	# itself end in eight digits.
	if [ -n "$(SNAPSHOT)" ]; then \
		echo "$(SNAPSHOT)" | grep -qE '^[0-9]{8}(\.[0-9]+)?$$' || { \
			echo "ERROR: SNAPSHOT must be YYYYMMDD with an optional .<respin> (got '$(SNAPSHOT)')"; \
			exit 1; \
		}; \
		UPSTREAM_VER="$${BASE_KVER_CLEAN}+git$(SNAPSHOT)"; \
		if [ -n "$(GITSHA)" ]; then \
			echo "$(GITSHA)" | grep -qE '^[0-9a-f]{12}$$' || { \
				echo "ERROR: GITSHA must be 12 lowercase hex characters (got '$(GITSHA)')"; \
				exit 1; \
			}; \
			UPSTREAM_VER="$${UPSTREAM_VER}~g$(GITSHA)"; \
		fi; \
	else \
		UPSTREAM_VER="$${BASE_KVER_CLEAN}"; \
	fi; \
	PKG_VERSION="$${UPSTREAM_VER}-$(DEBIAN_REVISION)"; \
	echo "Package version: $$PKG_VERSION"; \
	\
	# ── Derive HDRPKG from BINPKG ─────────────────────────────────────────────
	HDRPKG=$$(echo "$(BINPKG)" | sed 's/^linux-image-/linux-headers-/'); \
	\
	# ── Resolve the DKMS module list ──────────────────────────────────────────
	# One CSV list drives both generated artifacts: the Build-Depends entries in
	# debian/control (so the -dkms packages are present in the build chroot) and
	# the debian/dkms-modules manifest (so the bundler builds exactly those).
	# Deriving both from the same variable is what keeps them from drifting.
	DKMS_LIST=""; \
	for mod in $$(echo "$(DKMS_MODULES)" | tr ',' ' '); do \
		case "$$mod" in \
			*-dkms) \
				echo "ERROR: DKMS_MODULES entries must omit the -dkms suffix (got '$$mod'; use '$${mod%-dkms}')"; \
				exit 1 ;; \
		esac; \
		echo "$$mod" | grep -qE '^[a-z0-9][a-z0-9+.-]*$$' || { \
			echo "ERROR: invalid DKMS module name: '$$mod'"; \
			echo "       Expected a package name stem, e.g. DKMS_MODULES=kgsl,camx"; \
			exit 1; \
		}; \
		case " $$DKMS_LIST " in \
			*" $$mod "*) echo "ERROR: duplicate DKMS module in DKMS_MODULES: $$mod"; exit 1 ;; \
		esac; \
		DKMS_LIST="$$DKMS_LIST $$mod"; \
	done; \
	DKMS_LIST="$${DKMS_LIST# }"; \
	\
	# Build-Depends tail appended after the last unconditional entry, so an
	# empty list leaves the field exactly as control.in spells it — no dangling
	# comma, and no dkms tooling pulled into a build that bundles nothing.
	DKMS_BUILD_DEPENDS=""; \
	if [ -n "$$DKMS_LIST" ]; then \
		for mod in $$DKMS_LIST; do \
			DKMS_BUILD_DEPENDS="$$DKMS_BUILD_DEPENDS, $$mod-dkms"; \
		done; \
		DKMS_BUILD_DEPENDS=", dkms$$DKMS_BUILD_DEPENDS"; \
	fi; \
	\
	# ── Substitute templates ──────────────────────────────────────────────────
	sed \
		-e "s|@SRCPKG@|$(SRCPKG)|g" \
		-e "s|@BINPKG@|$(BINPKG)|g" \
		-e "s|@HDRPKG@|$$HDRPKG|g" \
		-e "s|@KVER@|$$KVER_RESOLVED|g" \
		-e "s|@PKGVER@|$$PKG_VERSION|g" \
		-e "s|@DKMS_BUILD_DEPENDS@|$$DKMS_BUILD_DEPENDS|g" \
		debian/control.in > debian/control; \
	\
	# One group of binary package stanzas per bundled module, appended to the
	# generated control. Every module named in DKMS_MODULES ships as its own
	# <name>-modules-<kver> package rather than being copied into the image, so
	# the stanzas cannot be spelled in control.in: there is one per entry in a
	# list that is a build input.
	#
	# Appended from the same DKMS_LIST that drives Build-Depends and the
	# dkms-modules manifest, so a module cannot be declared in control without
	# also being built, or built without being declared.
	for mod in $$DKMS_LIST; do \
		printf '\n' >> debian/control; \
		sed \
			-e "s|@MODNAME@|$$mod|g" \
			-e "s|@KVER@|$$KVER_RESOLVED|g" \
			-e "s|@BINPKG@|$(BINPKG)|g" \
			debian/control-dkms.in >> debian/control; \
	done; \
	\
	# One more stanza, once, when anything was bundled: the metapackage that
	# pulls in every per-module metapackage above, so the whole out-of-tree
	# module set for a variant installs under a single name.
	# It depends on those metapackages rather than on the versioned packages,
	# so what it names does not have to be re-resolved on every snapshot.
	if [ -n "$$DKMS_LIST" ]; then \
		DKMS_META_DEPENDS=""; \
		for mod in $$DKMS_LIST; do \
			DKMS_META_DEPENDS="$$DKMS_META_DEPENDS, $(BINPKG)-modules-$$mod (= \$${binary:Version})"; \
		done; \
		printf '\n' >> debian/control; \
		sed \
			-e "s|@BINPKG@|$(BINPKG)|g" \
			-e "s|@DKMS_META_DEPENDS@|$$DKMS_META_DEPENDS|g" \
			debian/control-dkms-all.in >> debian/control; \
	fi; \
	sed \
		-e "s|@SRCPKG@|$(SRCPKG)|g" \
		-e "s|@PKGVER@|$$PKG_VERSION|g" \
		-e "s|@DISTRO@|$(DISTRO)|g" \
		-e "s|@KVER@|$$KVER_RESOLVED|g" \
		-e "s|@GITCLONE@|$(GIT_CLONE)|g" \
		-e "s|@BRANCH@|$(GIT_REF)|g" \
		-e "s|@GITSHA@|$(GIT_SHA)|g" \
		-e "s|@DATE@|$(CHANGELOG_DATE)|g" \
		debian/changelog.in > debian/changelog; \
	\
	# ── Write runtime state files ─────────────────────────────────────────────
	# debian/localversion: the full kernel suffix passed to make LOCALVERSION=,
	# read by override_dh_auto_build. Includes KVER_EXTRA when set so that the
	# suffix used at build time matches the package name declared at prepare time.
	printf '%s\n' "$(LOCALVERSION)$(KVER_EXTRA)" > debian/localversion; \
	\
	# debian/pkgversion: the full Debian package version, read by override_dh_gencontrol.
	printf '%s\n' "$$PKG_VERSION" > debian/pkgversion; \
	\
	# debian/dkms-modules: the manifest read at build time by
	# debian/scripts/bundle-dkms-modules.sh. Written unconditionally — the
	# bundler treats a missing manifest as a misconfiguration and a comment-only
	# one as a legitimate empty module set.
	{ \
		echo "# Generated by debian/rules prepare from DKMS_MODULES — do not edit."; \
		echo "# One module name per line, without the -dkms suffix."; \
		echo "# Pass DKMS_MODULES=<csv> to 'prepare' (prepare-source.sh --dkms) to change it."; \
		for mod in $$DKMS_LIST; do echo "$$mod"; done; \
	} > debian/dkms-modules; \
	\
	echo "Generated debian/control, debian/changelog, debian/localversion, debian/pkgversion, debian/dkms-modules"; \
	echo "  SRCPKG=$(SRCPKG)  BINPKG=$(BINPKG)  HDRPKG=$$HDRPKG"; \
	echo "  KVER=$$KVER_RESOLVED  PKGVER=$$PKG_VERSION  DISTRO=$(DISTRO)"; \
	echo "  DKMS modules: $${DKMS_LIST:-(none)}"

override_dh_auto_configure:
	# ---------------------------------------------------------------------------
	# Config build order:
	#   1. ARM64 base defconfig
	#   2. Disable CONFIG_LOCALVERSION_AUTO (must happen before any merges)
	#   3. Config fragments applied in a single unified pipeline:
	#        a. arch/arm64/configs/prune.config  (kernel-source, always applied if present)
	#        b. arch/arm64/configs/qcom.config   (kernel-source, always applied if present)
	#        c. debian/config/*.config            (packaging fragments)
	#           Populated by prepare-source.sh: every fragment in
	#           debian/config-available/, plus any intree: fragments named in
	#           --kernel-config. Applied in LC_ALL=C filename order so the
	#           result does not depend on the builder's locale.
	#      All fragments are merged in one scripts/kconfig/merge_config.sh -m -r
	#      invocation (later fragments win, overrides are reported), followed by
	#      make olddefconfig to resolve the resulting dependencies.
	#   4. Re-check CONFIG_LOCALVERSION_AUTO (merges may re-enable it)
	# ---------------------------------------------------------------------------

	# Step 1: Base defconfig
	$(MAKE) $(KBUILD_O_ARG) ARCH=$(ARCH) defconfig

	# Step 2: Disable CONFIG_LOCALVERSION_AUTO to prevent git hash in version.
	@CONFIG_FILE="$(if $(BUILD_OBJ),$(BUILD_OBJ)/).config"; \
	if [ -f "$$CONFIG_FILE" ]; then \
		echo "Disabling CONFIG_LOCALVERSION_AUTO in $$CONFIG_FILE"; \
		sed -i '/^CONFIG_LOCALVERSION_AUTO/d' "$$CONFIG_FILE"; \
		echo "# CONFIG_LOCALVERSION_AUTO is not set" >> "$$CONFIG_FILE"; \
		echo "CONFIG_LOCALVERSION_AUTO disabled"; \
	else \
		echo "ERROR: .config not found at $$CONFIG_FILE"; \
		exit 1; \
	fi

	# Step 3: Unified config fragment pipeline.
	@CONFIG_FILE="$(if $(BUILD_OBJ),$(BUILD_OBJ)/).config"; \
	FRAGMENTS=""; \
	if [ -f arch/arm64/configs/prune.config ]; then \
		echo "Found kernel-source fragment: arch/arm64/configs/prune.config"; \
		FRAGMENTS="arch/arm64/configs/prune.config"; \
	else \
		echo "Note: arch/arm64/configs/prune.config not found (skipping)"; \
	fi; \
	if [ -f arch/arm64/configs/qcom.config ]; then \
		echo "Found kernel-source fragment: arch/arm64/configs/qcom.config"; \
		FRAGMENTS="$$FRAGMENTS arch/arm64/configs/qcom.config"; \
	else \
		echo "Note: arch/arm64/configs/qcom.config not found (not a qcom-next tree?)"; \
	fi; \
	if [ -d debian/config ] && ls debian/config/*.config >/dev/null 2>&1; then \
		for f in $$(ls debian/config/*.config | LC_ALL=C sort); do \
			echo "Found packaging fragment: $$f"; \
			FRAGMENTS="$$FRAGMENTS $$f"; \
		done; \
	else \
		echo "Note: no packaging fragments in debian/config/ (none activated via --kernel-config)"; \
	fi; \
	if [ -n "$$FRAGMENTS" ]; then \
		[ -x scripts/kconfig/merge_config.sh ] || { \
			echo "ERROR: scripts/kconfig/merge_config.sh not found or not executable"; \
			exit 1; \
		}; \
		echo "Merging config fragments into $$CONFIG_FILE:$$FRAGMENTS"; \
		ARCH=$(ARCH) scripts/kconfig/merge_config.sh -m -r \
			$(if $(BUILD_OBJ),-O $(BUILD_OBJ)) \
			"$$CONFIG_FILE" $$FRAGMENTS; \
		echo "Running olddefconfig to resolve all fragment conflicts..."; \
		$(MAKE) $(KBUILD_O_ARG) ARCH=$(ARCH) olddefconfig; \
	else \
		echo "No config fragments to apply (defconfig only)"; \
	fi

	# Step 4: Re-check CONFIG_LOCALVERSION_AUTO — merges may have re-enabled it.
	@CONFIG_FILE="$(if $(BUILD_OBJ),$(BUILD_OBJ)/).config"; \
	if grep -q "^CONFIG_LOCALVERSION_AUTO=y" "$$CONFIG_FILE" 2>/dev/null; then \
		echo "Re-disabling CONFIG_LOCALVERSION_AUTO (was re-enabled by a config merge)"; \
		sed -i '/^CONFIG_LOCALVERSION_AUTO/d' "$$CONFIG_FILE"; \
		echo "# CONFIG_LOCALVERSION_AUTO is not set" >> "$$CONFIG_FILE"; \
	fi

override_dh_auto_build:
	# Read LOCALVERSION from debian/localversion (written by 'prepare' target).
	# This avoids the fragile back-derivation from the source package name that
	# broke when the source package name no longer encodes the kernel version.
	@[ -f debian/localversion ] || { \
		echo "ERROR: debian/localversion not found."; \
		echo "       Run 'make -f debian/rules prepare LOCALVERSION=...' first."; \
		exit 1; \
	}; \
	LOCALVER_SUFFIX=$$(cat debian/localversion); \
	echo "Building with LOCALVERSION=$$LOCALVER_SUFFIX"; \
	$(MAKE) $(KBUILD_O_ARG) ARCH=$(ARCH) LOCALVERSION=$$LOCALVER_SUFFIX -j$(PARALLEL) Image; \
	$(MAKE) $(KBUILD_O_ARG) ARCH=$(ARCH) LOCALVERSION=$$LOCALVER_SUFFIX -j$(PARALLEL) modules; \
	$(MAKE) $(KBUILD_O_ARG) ARCH=$(ARCH) LOCALVERSION=$$LOCALVER_SUFFIX -j$(PARALLEL) dtbs || true; \
	mkdir -p $(dir $(KREL_FILE)); \
	KREL=$$( $(MAKE) $(KBUILD_O_ARG) ARCH=$(ARCH) LOCALVERSION=$$LOCALVER_SUFFIX -s kernelrelease 2>&1 | grep -E '^[0-9]+\.' | head -n1 ); \
	printf "%s\n" "$$KREL" > "$(KREL_FILE)"; \
	echo "Kernel release (uname -r): $$KREL"

override_dh_auto_install:
	# Derive all binary package staging directory names from BASE (uname -r),
	# not from the source package name. The source package name (linux-qcom-next)
	# no longer encodes the kernel version, so it cannot be used for derivation.
	@BASE=$$(cat $(KREL_FILE)); \
	echo "Installing for kernel release: $$BASE"; \
	# Assert that the package name declared at prepare time matches the kernel
	# release produced at build time. A mismatch (e.g. KVER_EXTRA set but not
	# written to debian/localversion) would produce empty staging directories
	# and silently empty packages with no other diagnostic.
	EXPECTED_PKG=$$(grep '^Package:' debian/control | head -n1 | sed 's/^Package: //'); \
	ACTUAL_PKG="linux-image-$$BASE"; \
	if [ "$$EXPECTED_PKG" != "$$ACTUAL_PKG" ]; then \
		echo "ERROR: package name mismatch: control declares $$EXPECTED_PKG but kernelrelease is $$BASE"; \
		echo "       Check that LOCALVERSION and KVER_EXTRA are consistent between prepare and build."; \
		exit 1; \
	fi; \
	PKG=debian/linux-image-$$BASE; \
	HDR_PKG=debian/linux-headers-$$BASE; \
	DBG_PKG=debian/linux-image-$$BASE-dbg; \
	\
	# Resolve object dir (if any)
	OBJ_DIR="$(BUILD_OBJ)"; \
	IMG_DIR="arch/arm64/boot"; \
	DTB_ROOT="arch/arm64/boot/dts/"; \
	if [ -n "$$OBJ_DIR" ]; then \
		IMG_DIR="$$OBJ_DIR/$$IMG_DIR"; \
		DTB_ROOT="$$OBJ_DIR/$$DTB_ROOT"; \
	fi; \
	\
	# Pick the first available kernel image: Image, Image.gz, or Image.lz4
	IMG_PATH=""; \
	for cand in "$$IMG_DIR/Image" "$$IMG_DIR/Image.gz" "$$IMG_DIR/Image.lz4"; do \
		if [ -f "$$cand" ]; then IMG_PATH="$$cand"; break; fi; \
	done; \
	[ -n "$$IMG_PATH" ] || { echo "ERROR: No kernel image found under $$IMG_DIR (tried Image, Image.gz, Image.lz4)"; exit 1; }; \
	[ -d "$$DTB_ROOT" ] || { echo "ERROR: Missing DTB root at $$DTB_ROOT"; exit 1; }; \
	\
	# Locate the active .config (objdir-aware)
	CFG_PATH=".config"; \
	[ -n "$$OBJ_DIR" ] && CFG_PATH="$$OBJ_DIR/.config"; \
	[ -f "$$CFG_PATH" ] || { echo "ERROR: Missing .config at $$CFG_PATH"; exit 1; }; \
	\
	# Locate System.map (objdir-aware). Required, not optional: the depmod
	# snippet debhelper generates for every package shipping a module is
	# guarded by [ -e /boot/System.map-<kver> ], so without this file the
	# snippet is a no-op and nothing on the target ever regenerates
	# modules.dep.
	MAP_PATH="System.map"; \
	[ -n "$$OBJ_DIR" ] && MAP_PATH="$$OBJ_DIR/System.map"; \
	[ -f "$$MAP_PATH" ] || { echo "ERROR: Missing System.map at $$MAP_PATH"; exit 1; }; \
	\
	# /boot artifacts
	mkdir -p "$$PKG/boot"; \
	cp -a -T "$$IMG_PATH" "$$PKG/boot/vmlinuz-$$BASE"; \
	cp -a -T "$$CFG_PATH" "$$PKG/boot/config-$$BASE"; \
	cp -a -T "$$MAP_PATH" "$$PKG/boot/System.map-$$BASE"; \
	\
	# Modules (stripped). kbuild installs them under lib/modules/ in the staging
	# tree; execute_after_dh_installdeb moves them to /usr/lib/modules/.
	$(MAKE) $(KBUILD_O_ARG) ARCH=$(ARCH) modules_install \
		INSTALL_MOD_PATH=$$PKG INSTALL_MOD_STRIP=1; \
	\
	# Fix build/source symlinks to point at the installed headers package.
	rm -f $$PKG/lib/modules/$$BASE/build; \
	rm -f $$PKG/lib/modules/$$BASE/source; \
	ln -sf /usr/src/linux-headers-$$BASE $$PKG/lib/modules/$$BASE/build; \
	ln -sf /usr/src/linux-headers-$$BASE $$PKG/lib/modules/$$BASE/source; \
	\
	# DTBs: standard Debian location /usr/lib/linux-image-<BASE>/
	mkdir -p $$PKG/usr/lib/linux-image-$$BASE; \
	rsync -a --prune-empty-dirs \
	      --include='*/' --include='*.dtb' --include='*.dtbo' --exclude='*' \
	      "$$DTB_ROOT" $$PKG/usr/lib/linux-image-$$BASE/; \
	\
	# Ubuntu flash-kernel compatibility symlink:
	#   /usr/lib/firmware/<BASE>/device-tree -> ../../linux-image-<BASE>
	# Relative symlink so it resolves correctly on both classic and usrmerge systems.
	mkdir -p $$PKG/usr/lib/firmware/$$BASE; \
	ln -sfT ../../linux-image-$$BASE $$PKG/usr/lib/firmware/$$BASE/device-tree; \
	\
	# Kernel headers for linux-headers-<BASE> package.
	# Pass 1: source-tree files (Makefile, include/, scripts/, arch/arm64/ headers).
	# Pass 2: build-directory generated files (overlay on Pass 1).
	# Note: make headers_install (UAPI) is intentionally NOT run — it corrupts
	# kernel-internal headers (bitsperlong.h) and breaks DKMS/out-of-tree builds.
	HDRDIR="$$HDR_PKG/usr/src/linux-headers-$$BASE"; \
	echo "Installing kernel headers to $$HDRDIR"; \
	mkdir -p "$$HDRDIR"; \
	cp -a Makefile "$$HDRDIR/"; \
	cp -a include "$$HDRDIR/"; \
	cp -a scripts "$$HDRDIR/"; \
	mkdir -p "$$HDRDIR/arch/arm64"; \
	find arch/arm64 -maxdepth 1 -name 'Makefile*' \
	    -exec cp -a {} "$$HDRDIR/arch/arm64/" \; 2>/dev/null || true; \
	[ -d arch/arm64/include ] && cp -a arch/arm64/include "$$HDRDIR/arch/arm64/"; \
	if [ -n "$$OBJ_DIR" ]; then \
		[ -d "$$OBJ_DIR/include/generated" ] && \
		    cp -a "$$OBJ_DIR/include/generated" "$$HDRDIR/include/"; \
		if [ -d "$$OBJ_DIR/arch/arm64/include/generated" ]; then \
		    mkdir -p "$$HDRDIR/arch/arm64/include"; \
		    cp -a "$$OBJ_DIR/arch/arm64/include/generated" "$$HDRDIR/arch/arm64/include/"; \
		fi; \
		[ -d "$$OBJ_DIR/scripts" ] && cp -a "$$OBJ_DIR/scripts/." "$$HDRDIR/scripts/"; \
		cp -a "$$OBJ_DIR/Module.symvers" "$$HDRDIR/" 2>/dev/null || true; \
		cp -a "$$OBJ_DIR/.config" "$$HDRDIR/"; \
	else \
		cp -a Module.symvers "$$HDRDIR/" 2>/dev/null || true; \
		cp -a .config "$$HDRDIR/"; \
	fi; \
	mkdir -p "$$HDRDIR/arch/arm64/kernel"; \
	MODULE_LDS="arch/arm64/kernel/module.lds"; \
	[ -n "$$OBJ_DIR" ] && MODULE_LDS="$$OBJ_DIR/arch/arm64/kernel/module.lds"; \
	cp -a "$$MODULE_LDS" "$$HDRDIR/arch/arm64/kernel/" 2>/dev/null || true; \
	\
	# Debug symbols for linux-image-<BASE>-dbg package.
	#
	# Each module's debug file is written twice over: once at the path that
	# mirrors where the module installs (/usr/lib/debug + /lib/modules/<ver>/
	# kernel/<path>), and once as a /usr/lib/debug/.build-id/xx/yyy.debug
	# symlink to it. Both are what scripts/package/builddeb produces.
	#
	# The build-id path is the one gdb, debuginfod and gdb-add-index consult
	# first, and the only one that does not depend on how the module was
	# addressed: a tool that opens it as /usr/lib/modules/... rather than
	# /lib/modules/... looks under /usr/lib/debug/usr/lib/modules/..., which
	# the mirrored path alone does not answer.
	echo "Installing debug symbols to $$DBG_PKG"; \
	MODULES_ORDER="modules.order"; \
	[ -n "$$OBJ_DIR" ] && MODULES_ORDER="$$OBJ_DIR/modules.order"; \
	if [ -f "$$MODULES_ORDER" ]; then \
		while IFS= read -r mod; do \
			mod="$${mod%.o}.ko"; \
			src_mod="$$mod"; \
			[ -n "$$OBJ_DIR" ] && src_mod="$$OBJ_DIR/$$mod"; \
			[ -f "$$src_mod" ] || continue; \
			dbg="$$DBG_PKG/usr/lib/debug/lib/modules/$$BASE/kernel/$$mod"; \
			mkdir -p "$${dbg%/*}"; \
			$(OBJCOPY) --only-keep-debug "$$src_mod" "$$dbg" 2>/dev/null || \
				cp -a "$$src_mod" "$$dbg"; \
			BUILDID=$$($(READELF) -n "$$src_mod" 2>/dev/null | \
			           sed -n 's@^.*Build ID: \(..\)\(.*\)@\1/\2@p'); \
			if [ -n "$$BUILDID" ]; then \
				link="$$DBG_PKG/usr/lib/debug/.build-id/$$BUILDID.debug"; \
				mkdir -p "$${link%/*}"; \
				ln -sf --relative "$$dbg" "$$link"; \
			else \
				echo "Warning: no build ID in $$mod — no .build-id symlink for it"; \
			fi; \
		done < "$$MODULES_ORDER"; \
	else \
		echo "Warning: modules.order not found — skipping per-module debug symbol extraction"; \
	fi; \
	VMLINUX_PATH="vmlinux"; \
	[ -n "$$OBJ_DIR" ] && VMLINUX_PATH="$$OBJ_DIR/vmlinux"; \
	if [ -f "$$VMLINUX_PATH" ]; then \
		mkdir -p $$DBG_PKG/usr/lib/debug/lib/modules/$$BASE; \
		cp -a $$VMLINUX_PATH $$DBG_PKG/usr/lib/debug/lib/modules/$$BASE/vmlinux; \
		mkdir -p $$DBG_PKG/usr/lib/debug/boot; \
		ln -sf ../lib/modules/$$BASE/vmlinux \
		       $$DBG_PKG/usr/lib/debug/boot/vmlinux-$$BASE; \
		ln -sf lib/modules/$$BASE/vmlinux \
		       $$DBG_PKG/usr/lib/debug/vmlinux-$$BASE; \
	else \
		echo "Warning: vmlinux not found at $$VMLINUX_PATH — debug package will not contain vmlinux"; \
	fi; \
	\
	# ── DKMS module integration ──────────────────────────────────────────────────
	# Delegated to debian/scripts/bundle-dkms-modules.sh.
	# The script reads debian/dkms-modules, builds each listed module against the
	# staging headers produced earlier in this same dpkg-buildpackage run, and
	# stages the resulting .ko files into debian/<name>-modules-<kver>/ and their
	# debug symbols into debian/<name>-modules-<kver>-dbg/ — the packages whose
	# control stanzas 'prepare' generated from the same manifest.
	# --image-pkg-dir is read, not written: the in-tree module list for the
	# collision check and boot/config-<kver> for BUILD_EXCLUSIVE_CONFIG analysis.
	# It can also be invoked directly by a developer — see the script's --help.
	$(CURDIR)/debian/scripts/bundle-dkms-modules.sh \
	    --kver            "$$BASE" \
	    --headers-dir     "$(CURDIR)/$$HDRDIR" \
	    --image-pkg-dir   "$(CURDIR)/$$PKG" \
	    --stage-root      "$(CURDIR)/debian" \
	    --arch            "$(DKMS_ARCH)" \
	    --objcopy         "$(OBJCOPY)" \
	    --modules-manifest "$(CURDIR)/debian/dkms-modules"

# Ignore files shipped in debug package.
override_dh_dwz:
	dh_dwz -X/usr/lib/debug/

# Ignore files shipped in debug package.
# Don't build "-dbgsym" packages.
override_dh_strip:
	dh_strip -X/usr/lib/debug/ --no-automatic-dbgsym

# Skip automatic dh_installmodules — called manually in override_dh_installdeb.
override_dh_installmodules:
	@echo "Skipping automatic dh_installmodules (called manually in override_dh_installdeb)"

override_dh_installdeb:
	# Generate versioned maintainer scripts from templates using BASE (uname -r).
	# The binary package name is linux-image-<BASE>, derived from kernel.release.
	# Every maintainer script is a debian/linux-image.<script>.in template with
	# @KVER@ substituted, so each one can name its own kernel release; scripts
	# with no template are simply not shipped.
	# dh_installmodules injects the depmod snippet at #DEBHELPER# in them.
	@BASE=$$(cat $(KREL_FILE)); \
	INST_PKG="linux-image-$$BASE"; \
	\
	for script in preinst postinst prerm postrm; do \
		template="debian/linux-image.$$script.in"; \
		[ -f "$$template" ] || continue; \
		sed "s/@KVER@/$$BASE/g" "$$template" > debian/$$INST_PKG.$$script; \
		chmod 755 debian/$$INST_PKG.$$script; \
	done; \
	\
	dh_installmodules; \
	dh_installdeb

# Move everything staged under the aliased /bin, /lib and /sbin directories
# into /usr, as Debian Policy 10.1 requires on merged-/usr systems: the
# modules and their build/source links from modules_install, and the bundled
# DKMS modules. kbuild hardcodes MODLIB to $(INSTALL_MOD_PATH)/lib/modules, so
# the modules are installed there and moved afterwards, the same way Debian's
# own linux package does it. dh_movetousr also rewrites the build/source links
# into the form Policy 10.5 requires.
#
# This must run after override_dh_installdeb rather than earlier in the
# sequence. dh_installmodules, which that override calls, only looks under
# lib/modules/ when deciding whether to add the depmod maintainer script
# snippet, so moving the modules first would silently drop it. The
# dh-sequence-movetousr addon runs the helper before dh_installdeb, which is
# still before that call, hence the explicit hook.
execute_after_dh_installdeb:
	dh_movetousr

override_dh_auto_test:
	@echo "Skipping dh_auto_test (no kernel test suite)."

override_dh_auto_clean:
	# Only clean the objdir if one is used; never nuke the source tree.
ifneq ($(BUILD_OBJ),)
	$(MAKE) $(KBUILD_O_ARG) clean
endif
	rm -f $(KREL_FILE)
	# Note: debian/localversion and debian/pkgversion are intentionally NOT
	# removed here. dpkg-buildpackage calls 'debian/rules clean' before the
	# build, so removing them here would delete the prepare-generated state
	# files before override_dh_auto_build and override_dh_gencontrol can read
	# them. They are listed in .gitignore and removed by 'git clean -fdx'.

override_dh_gencontrol:
	# Read the package version from debian/pkgversion (written by 'prepare' target).
	# This replaces the old hardcoded -v"1-1" which was only valid when the kernel
	# version was encoded entirely in the package name.
	#
	# Each per-module metapackage provides <name>-modules at the version of the
	# <name>-dkms source it was built from, passed in as the
	# $${<name>-dkms:Version} substvar for every module in debian/dkms-modules.
	@[ -f debian/pkgversion ] || { \
		echo "ERROR: debian/pkgversion not found."; \
		echo "       Run 'make -f debian/rules prepare ...' first."; \
		exit 1; \
	}; \
	PKG_VERSION=$$(cat debian/pkgversion); \
	echo "dh_gencontrol: Version=$$PKG_VERSION"; \
	DKMS_VARS=; \
	for mod in $$(sed -e 's/#.*//' -e 's/\r$$//' debian/dkms-modules); do \
		ver=$$(dpkg-query -W -f='$${Version}' "$$mod-dkms") || { \
			echo "ERROR: $$mod-dkms is not installed."; \
			exit 1; \
		}; \
		echo "dh_gencontrol: $$mod-dkms:Version=$$ver"; \
		DKMS_VARS="$$DKMS_VARS -V$$mod-dkms:Version=$$ver"; \
	done; \
	dh_gencontrol -- -v"$$PKG_VERSION" $$DKMS_VARS
