#!/usr/bin/make -f

# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1

BASEDIR:=$(shell pwd)
MODDIR:=$(BASEDIR)/kernel-image/modules/pcmcia-cs
MODTMP:=$(MODDIR)/debian/tmp-modules
MODULE_LOC:=$(BASEDIR)/kernel-image/modules

kvers:=$(shell grep ^Source: debian/control \
	| sed 's/^.*-\([^-]*\)-[^-]*$$/\1/')
debnum:=$(shell cd kernel-image && dh_listpackages | grep kernel-headers \
	| head -1 | sed 's/^.*\(-[0-9]*\)$$/\1/')
flavours:=$(shell find kernel-image/config -maxdepth 1 -type f ! -name default \
	-printf '%f\n')

source:=$(shell grep ^Source: debian/control | cut -d' ' -f2-)
maint:=$(shell grep ^Maintainer: debian/control | cut -d' ' -f2-)
version:=$(shell dpkg-parsechangelog | grep ^Version: | cut -d' ' -f2-)


unpack: unpack-stamp
unpack-stamp:
	dh_testdir

	cd kernel-image && tar xzf /usr/src/pcmcia-cs.tar.gz

	cd kernel-image && debian/rules unpack

	touch unpack-stamp

build: unpack
	dh_testdir

clean:
	dh_testdir
	dh_testroot

	rm -rf kernel-image/modules
	cd kernel-image && debian/rules clean
	rm -f *.deb kernel-image/*.deb
	rm -f unpack-stamp

	dh_clean

install: build
	dh_testdir
	dh_testroot

# Build architecture-independent files here.
binary-indep: build install
# We have nothing to do by default.

# Build architecture-dependent files here.
binary-arch: build install
	dh_testdir
	dh_testroot

# This is an ugly hack but what do you do...
	cd kernel-image && for i in $(flavours); do \
		cd build-$$i; \
		export MODULE_LOC=$(MODULE_LOC); \
		make-kpkg modules_clean; \
		FORCE_CONFIG_PCMCIA=y \
			make-kpkg modules_image --append_to_version \
			$(debnum)-$$i; \
		gzip -9c $(BASEDIR)/debian/changelog \
			> $(MODTMP)/usr/share/doc/pcmcia-modules-$(kvers)-$(debnum)-$$i/changelog.Debian.gz; \
		cat $(MODTMP)/DEBIAN/control | sed \
			-e 's/^Source: .*$$/Source: '$(source)'/' \
			-e 's/^Maintainer: .*$$/Maintainer: '"$(maint)"'/' \
			-e 's/^Version: .*$$/Version: '$(version)'/' \
			> $(MODTMP)/DEBIAN/control.new; \
		mv $(MODTMP)/DEBIAN/control.new $(MODTMP)/DEBIAN/control; \
		chown -R root.root $(MODTMP); \
		chmod -R g-ws $(MODTMP); \
		dpkg-deb --build $(MODTMP) ../../; \
		cd ..; \
	done

	for i in *.deb; do \
		dpkg-distaddfile $$i admin extra; \
	done
	mv *.deb ../

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