#!/bin/sh

rm -rf build
_KVER=$1
TMPDIR1=build
MAKEFILE="${TMPDIR1}/Makefile"
TEST_H="${TMPDIR1}/test.h"
TEST_C="${TMPDIR1}/test.c"

mkdir -p $TMPDIR1

config_host_h=config-host.h

rm -rf $config_host_h

remove_test() {
   make clean >> config.log 2>&1
   cd ..
   truncate -s 0 $TEST_C
}

output_sym() {
  echo "#define $1 1" >> $config_host_h
}

fatal() {
  echo $@
  echo "Configure failed, check config.log and/or the above output"
  rm -rf $config_host_h
  exit 1
}

compile_prog() {
   cd ${TMPDIR1}
   echo $1 '\n' >> config.log
   if [ $# -gt 1 ]; then
	kflags=$2
	make $kflags >> config.log 2>&1
   else
        make >> config.log 2>&1
   fi
   ret=$?
   if [ "$ret" -eq 0 ]
   then
        echo '\n' $1 "yes" >> config.log
	echo $1 "yes"
	echo '\n' "Invoking make clean" >> config.log
        remove_test
        return 0	
   else
        echo '\n' $1 "no"  >> config.log
        echo $1 "no"
	echo '\n' "Invoking make clean" >> config.log
        remove_test
	return 1
   fi
}

echo "/*" > $config_host_h
echo " * Automatically generated by configure - do not modify" >> $config_host_h
printf " * Configured with:" >> $config_host_h
printf " * '%s'" "$0" "$@" >> $config_host_h
echo "" >> $config_host_h
echo " */" >> $config_host_h

echo "#ifndef CONFIG_HOST_H" >> $config_host_h
echo "#define CONFIG_HOST_H" >> $config_host_h

#Check if KVER is already passed, if not assign the current kernel version
if [ -z "$_KVER" ]
then
	export KVER=$(uname -r)
else
	export KVER=${_KVER}
fi
export MODULES_DIR=/lib/modules/$KVER
export KDIR=$MODULES_DIR/build

cat > $MAKEFILE <<EOF
obj-m += test.o
all:
	make -j8 -C $KDIR M=$PWD/build modules
clean:
	make -j8 -C $KDIR M=$PWD/build clean
EOF

cat > $TEST_H <<EOF
#include <linux/module.h>
#include <linux/kernel.h>

MODULE_LICENSE("GPL v2");
EOF

cat > $TEST_C <<EOF
#include <linux/proc_fs.h>
#include "test.h"

int test (void)
{
	struct proc_ops ops;
	memset(&ops, 0, sizeof(struct proc_ops));
	return 0;
}
EOF
if compile_prog "Checking if struct proc_ops is present or not ..."; then
        output_sym "HAVE_STRUCT_PROC_OPS"
fi

echo "#endif" >> $config_host_h
rm -rf build
