#!/bin/sh -x

rm -f linux	# Cleaning up

# Only do the below on linux systems
if [ `uname -s` != Linux ]; then exit 0; fi

DEB_HOST_ARCH="$1"

# find kernel source. We build-depend on kernel-source-2.4, so it could
# be 2.4.7, 2.4.9, 2.4.123, ...

LINUXVER=`ls /usr/src |
    grep 'kernel-source-2.4.*tar.bz2' |
    tail -1 |
    sed 's,.*source-\(2.4.[^.]*\).tar..*,\1,'`

curdir=`pwd`
# powerpc shouldn't need to be special anymore
case $DEB_HOST_ARCH in
    XXXnot-powerpc)
	# On PowerPC the kernel needs to be reconfigured,
	# before we can build.  Otherwise we would create broken packages.
	rm -rf debian/kernel-source-$LINUXVER
	if [ -e /usr/src/kernel-source-$LINUXVER.tar.bz2 ]; then
	    cd debian
	    bzcat /usr/src/kernel-source-$LINUXVER.tar.bz2 | tar xf -
	    ln -sf debian/kernel-source-$LINUXVER ../linux
	    cp kernel-config-2.4.ppc ../linux/.config
	    cd ../linux && make oldconfig dep
	fi
	;;
    powerpc|alpha|arm|i386|ia64|m68k|mips|mipsel|sparc)
	if [ -e ../linux-for-isdnutils ]; then
	    # hack for maintainer to not (slowly) extract source everytime
	    ln -s ../linux-for-isdnutils linux
	fi
	if [ ! -e linux ]; then
	    cd debian
	    bzcat /usr/src/kernel-source-$LINUXVER.tar.bz2 |
		tar xf - kernel-source-$LINUXVER/drivers/isdn kernel-source-$LINUXVER/include
	    ln -sf debian/kernel-source-$LINUXVER ../linux
	    # now correct asm symlink
	    cd ../linux/include
	    rm -f asm && ln -s asm-$DEB_HOST_ARCH asm
	fi
	;;
    *)
        echo "Architecture not in powerpc|alpha|arm|i386|ia64|m68k|mips|mipsel|sparc"
        echo "so no need for kernel source."
        exit 0
        ;;
esac

# sanity check
cd $curdir
if [ ! -e linux -o ! -e linux/drivers/isdn/isdn_tty.h ]; then
    echo "kernel source not found!!"
    exit 1
fi

exit 0
