#!/bin/sh

DEFAULTKERNELDIR=/usr/src/linux
DEFREGEXP="#define.*CONFIG_REGPARM.*1"
CONFREGEXP="CONFIG_REGPARM=y"

REGPARM=n
FORCE=n
KERNELDIR=""

if (test "$1" = "regparm"); then
    REGPARM=y
    FORCE=y
elif (test "$1" = "noregparm"); then
    REGPARM=n
    FORCE=y
else
    KERNELDIR=$1
    if (test -z $KERNELDIR); then
        KERNELDIR=$DEFAULTKERNELDIR
    fi
fi

AUTOCONFH=$KERNELDIR/include/linux/autoconf.h
CONFIGH=$KERNELDIR/include/linux/config.h
KCONFIG=$KERNELDIR/.config
AUTOCONF=$KERNELDIR/include/config/auto.conf
MAKEFILE=$KERNELDIR/Makefile

if (test $FORCE = n); then
    if !(test -d $KERNELDIR); then
        echo "No kernel source directory found - exiting"
        exit 1
    fi

    echo "Using $KERNELDIR for CONFIG_REGPARM detection"
fi

if (test $FORCE = y); then
    echo "using override - no CONFIG_REGPARM detection"
elif (test `grep "^SUBLEVEL = " $MAKEFILE | sed -e "s/.*= *\([0-9]*\).*/\1/"` -gt 19); then
    echo "detected kernel revision > 2.6.19"
    REGPARM=y
else
    CHECKED=n
    if (test -e $AUTOCONFH); then
        echo "checking include/linux/autoconf.h"
        if (grep -q $DEFREGEXP $AUTOCONFH); then
            REGPARM=y
        fi
        CHECKED=y
    fi
    if ((test -r $CONFIGH) && (test $REGPARM = "n")); then
        echo "checking include/linux/config.h"
        if (grep -q $DEFREGEXP $CONFIGH); then
            REGPARM=y
        fi
        CHECKED=y
    fi
    if ((test -r $AUTOCONF) && (test $REGPARM = "n")); then
        echo "checking include/config/auto.conf"
        if (grep -q $CONFREGEXP $AUTOCONF); then
            REGPARM=y
        fi
        CHECKED=y
    fi
    if ((test -r $KCONFIG) && (test $CHECKED = "n")); then
        echo "checking .config (fallback) - please check your kernel configuration"
        if grep -q $CONFREGEXP $KCONFIG; then
            REGPARM=y
        fi
        CHECKED=y
    elif (test $CHECKED = "n"); then
        echo "no configuration found, asuming CONFIG_REGPARM=y"
        echo "please check your kernel configuration"
        REGPARM=y
    fi
fi

if (test $REGPARM = y) ; then
    echo " => CONFIG_REGPARM active"
    cp jidap.a.regparm jidap.a
else
    echo " => CONFIG_REGPARM not activated"
    cp jidap.a.noregparm jidap.a
fi

echo " => JIDA won't work correctly if this setting does not match the actual kernel"
echo "    configuration."
echo " => You can override the detection by using \"make [no]regparm\" to build the"
echo "    JIDA kernel module in the JidaDrv directory."
echo " => Please have a look at the \"Use register Arguments\" option in the kernel"
echo "    configuration section \"Processor type and features\" to learn more."
echo
