#!/bin/sh

set -e

debhelper_pre() {
	dh_clean -k --package="$1"
	dh_installdirs --package="$1"
}

debhelper_post() {
	dh_installdocs --package="$1"
	dh_installchangelogs --package="$1"
	dh_compress --package="$1"
	dh_fixperms --package="$1"
	dh_installdeb --package="$1"
	dh_gencontrol --package="$1"
	dh_md5sums --package="$1"
	dh_builddeb --package="$1"
}


suffix=${version#*$debnum-}
prefix=${version%%-*}$debnum
pkg=kernel-headers-$version
top=$PWD/debian/$pkg
dir=$top/usr/src/kernel-headers-$version

karch=${suffix%-smp}
karch=${karch%32}

debhelper_pre $pkg

mkdir -p $dir/include/linux
cp -a .config $dir
echo $debnum-$suffix > $dir/.extraversion
cp -a Module.symvers $dir

find . -mindepth 1 -maxdepth 1 \
	! -name debian -a ! -name Documentation -a ! -name include -a \
	! -name '.*' -a \( \
	-name Makefile -o -type d \) \
	-printf "../kernel-headers-$prefix/%f\n" |
	xargs ln -s --target-directory="$dir"

cd include
find . -mindepth 1 -maxdepth 1 \
	! -name config -a ! -name linux -a \( \
	! -name 'asm-*' -o -name asm-generic -o -name asm-$karch \) \
	-printf "../../kernel-headers-$prefix/include/%f\n" |
	xargs ln -s --target-directory=$dir/include
cp -a config $dir/include
ln -sf asm-$karch $dir/include/asm
find linux -mindepth 1 -maxdepth 1 \
	! -name autoconf.h -a ! -name compile.h -a ! -name version.h \
	-printf "../../../kernel-headers-$prefix/include/linux/%f\n" |
	xargs ln -s --target-directory=$dir/include/linux
cp -a linux/autoconf.h linux/compile.h \
	linux/version.h $dir/include/linux
cd ..

mkdir -p $top/lib/modules/$version
ln -s /usr/src/kernel-headers-$version $top/lib/modules/$version/build

debhelper_post $pkg
 
bpkg=kernel-build-$prefix
top=$PWD/../debian/$bpkg

[ -d $top/usr/src/$bpkg ] || mkdir -p $top/usr/src/$bpkg
ln -s ../kernel-headers-$version $top/usr/src/$bpkg/$suffix
