#!/bin/bash

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_shlibdeps --package="$1"
	dh_installdeb --package="$1"
	dh_gencontrol --package="$1"
	dh_md5sums --package="$1"
	dh_builddeb --package="$1"
}


stem=${STEM:-kernel}
suffix=${version#*$debnum-}
prefix=$DEBIAN_UPSTREAM_VERSION$debnum
pkg=$stem-headers-$version
pkg_d=$stem-image-debug-$version
top=$PWD/debian/$pkg
top_d=$PWD/debian/$pkg_d
dir=$top/usr/src/$stem-headers-$version


# Headers
debhelper_pre $pkg

install -d $dir/include/linux

cp -a .config $dir
cp -a Module.symvers $dir

find . -mindepth 1 -maxdepth 1 \
	! -name debian -a ! -name Documentation -a ! -name include -a \
	! -name modules -a ! -name firmware -a ! -name '.*' -a \
	! -name scripts -a \
	-type d \
	-printf "../$stem-headers-$prefix/%f\n" |
	xargs ln -s --target-directory=$dir

cat Makefile | sed "s/^EXTRAVERSION *=[^$].*/EXTRAVERSION=$debnum-$suffix/" > \
	$dir/Makefile

cd include
find . -mindepth 1 -maxdepth 1 \
	! -name config -a ! -name linux \
	-printf "../../$stem-headers-$prefix/include/%f\n" |
	xargs ln -s --target-directory=$dir/include

# fix asm link to the proper arch
KARCH=$(grep "^headers-$KPKG_ARCH[[:space:]]" ../../../config/archmap | grep -v ^# | awk '{print $2}')

rm -f $dir/include/asm
ln -sf asm-$KARCH $dir/include/asm

cp -a config $dir/include
find linux -mindepth 1 -maxdepth 1 \
	! -name autoconf.h -a \
	! -name compile.h -a ! -name version.h -a \
	! -name utsrelease.h \
	-printf "../../../$stem-headers-$prefix/include/linux/%f\n" |
	xargs ln -s --target-directory=$dir/include/linux
cp -a linux/autoconf.h linux/compile.h linux/utsrelease.h \
	linux/version.h $dir/include/linux
cd ..

cp -a scripts $dir

install -d $top/lib/modules/$version
ln -s /usr/src/$stem-headers-$version $top/lib/modules/$version/build

debhelper_post $pkg
install -d $dir/include/linux

# Debug package
debhelper_pre $pkg_d

install -D -m 644 vmlinux $top_d/boot/vmlinux-dbg-$version

debhelper_post $pkg_d


cd "$IMAGE_TOP/lib/modules/$version"
if [ -h source ]; then
	rm source
fi
install -d initrd
if [ -f kernel/drivers/video/vesafb.ko ]; then
	ln -f kernel/drivers/video/vesafb.ko initrd/
fi
if [ -f kernel/security/capability.ko ]; then
	ln -f kernel/security/capability.ko initrd/
fi

cd ../../..
install -d lib/firmware/$version
# zd1211 needs to stay in the subdirectory
cp -a "$DEBIAN_SRCTOP"/debian/firmware/zd1211 lib/firmware/$version/
for i in "$DEBIAN_SRCTOP"/debian/firmware/*/[[:lower:]]*; do
	case ${i##*/} in
		zd12*)
			;;
		*)
			cp $i "lib/firmware/$version/${i##*/}"
			;;
	esac
done
