#! /bin/bash

if [ -z "${KERNEL_DIR}" ]; then
	for tryKernelDir in "/lib/modules/$(uname -r)"/{build,source} "/usr/src/linux-$(uname -r)"; do
		if [ -f "${tryKernelDir}/.config" ]; then
			kernelDir="${tryKernelDir}"

			break
		fi
	done

else
	kernelDir="${KERNEL_DIR}"
fi

if [ -z "${kernelDir}" ]; then
	echo "error: Unable to determine kernel build directory.  Try specifying the KERNEL_DIR environment variable" >&2

	exit 1
fi

if [ -z "${SYSTEM_MAP_FILE}" ]; then
	for trySystemMapFile in /proc/kallsyms "${kernelDir}/System.map" "/boot/System.map"; do
		if egrep ' sys_call_table($| )' "${trySystemMapFile}" >/dev/null 2>/dev/null; then
			systemMapFile="${trySystemMapFile}"

			break
		fi
	done
else
	systemMapFile="${SYSTEM_MAP_FILE}"
fi

if [ -z "${systemMapFile}" ]; then
	echo "error: Unable to determine system map file.  Try specifying the SYSTEM_MAP_FILE environment variable." >&2

	exit 1
fi

rm -f Makefile.inc
echo "SYSTEM_MAP_FILE = ${systemMapFile}" > Makefile.inc
echo "KERNEL_DIR = ${kernelDir}" >> Makefile.inc
echo "KERNEL_VER = $(uname -r)" >> Makefile.inc

exit 0
