#!/usr/bin/make -f
#
# debian/rules for kernel-source.
#
# GNU copyright 1997 to 1999 by Joey Hess.
# Copyright (c) 1999-2004 Herbert Xu <herbert@gondor.apana.org.au>
# Copyright (c) 2004 Jens Schmalzing <jensen@debian.org>
#

# Pull out the source suffix, we intend to maintain an -lts-<series> suffix
# but otherwise assume this main packages are not intended to have a suffix
# so that linux-meta and linux-meta-ti-omap4 will behave normally, but
# linux-meta-lts-vivid will add the series suffix.
SERIES=$(shell dpkg-parsechangelog | sed -ne 's/^Distribution: *//p' | sed -e 's/-\(security\|updates\|proposed\)$$//')
SOURCE=$(shell dpkg-parsechangelog | sed -ne 's/^Source: *//p')

# 5 digit versions (2.6.38.<abi>.<upload>, 3 digit kernel base versions (2.6.38)
KERNEL_VERSION=$(shell dpkg-parsechangelog | grep ^Version | sed -e \
	's/Version: \([0-9]*\.[0-9]*\.[0-9]*\)\..*/\1/')
KERNEL_ABI=$(shell head -n1 < debian/changelog | gawk '{n=split($$0,v,"."); print v[4];}')

# 4 digit versions (3.0.<abi>.<upload>), 2 digit kernel base versions (3.0)
#KERNEL_VERSION=$(shell dpkg-parsechangelog | grep ^Version | sed -e \
	's/Version: \([0-9]*\.[0-9]*\)\..*/\1/')
#KERNEL_ABI=$(shell head -n1 < debian/changelog | gawk '{n=split($$0,v,"."); print v[3];}')

KERNEL_ABI_VERSION=$(KERNEL_VERSION)-$(KERNEL_ABI)

control_files := debian/control.common $(shell LC_ALL=C ls -d debian/control.d/*)

SHELL := sh -e

build:
	dh_testdir

clean: debian/control
	dh_testdir
	dh_testroot
	dh_clean

# Variants -- is prime and implies no suffix.
# Possible elements: -- -edge -lts-18.04
variants=-- -edge

define variant_payload
variant="$$(echo '$(variant)' | sed -e 's/--//')"; \
sed -e "s/\$${variant:suffix}/$$variant/g" <$$i; \
echo "";
endef

debian/control: $(control_files)
	for i in $^; do \
		if grep -q "{variant:" $$i; then \
			$(foreach variant,$(variants),$(variant_payload)) \
		else \
			cat $$i; \
			echo ""; \
		fi; \
	done | sed \
		-e 's/@SERIES@/$(SERIES)/g' \
		-e 's/$${kernel-abiver}/$(KERNEL_ABI_VERSION)/g' \
	    >$@.tmp
	rm -f $@
	mv debian/control.tmp $@

install: build
	dh_testdir
	dh_testroot
	dh_clean -k

gencontrol_flags = -Vkernel-version=$(KERNEL_VERSION)
gencontrol_flags += -Vkernel-abi-version=$(KERNEL_ABI_VERSION)

# Build architecture-independent files here.
binary-indep: debian/control install
	dh_testdir
	dh_testroot

	dh_installdirs -i
	dh_installdocs -i
	dh_installchangelogs -i
	dh_compress -i
	dh_fixperms -i
	dh_installdeb -i
	dh_gencontrol -i -- $(gencontrol_flags)
	dh_md5sums -i
	dh_builddeb -i

# Build architecture-dependent files here.
binary-arch: debian/control install
	dh_testdir
	dh_testroot

	dh_installdirs -s
	dh_installdocs -s
	dh_installchangelogs -s
	dh_compress -s
	dh_fixperms -s
	dh_installdeb -s
	dh_gencontrol -s -- $(gencontrol_flags)
	dh_md5sums -s
	dh_builddeb -s

binary: binary-indep binary-arch

.PHONY: build clean binary-indep binary-arch binary install
