#!/bin/bash
set +e
set +E

#
# Some modules like r8168 doest recompile at new kernel installs, so this hook does a kind of dpkg-reconfigure for all the dkms modules, just in case
#

# distro version
# case "$( cat /etc/debian_version )" in
#     7.*|"wheezy"*)
#         is_wheezy=1
#         ;;
# esac
# temporally disabled: probably we don't need this hack anymore
# if ! ((is_wheezy)) ; then
#     exit
# fi
#
# don't run anything on live mode
if grep -qs "boot=live" /proc/cmdline ; then
    exit 0
fi

# We're passed the version of the kernel being installed
inst_kern=$1

uname_s=$(uname -s)

_get_kernel_dir() {
    KVER=$1
    case ${uname_s} in
       Linux)          DIR="/lib/modules/$KVER/build" ;;
       GNU/kFreeBSD)   DIR="/usr/src/kfreebsd-headers-$KVER/sys" ;;
    esac
    echo $DIR
}

_check_kernel_dir() {
    DIR=$(_get_kernel_dir $1)
    case ${uname_s} in
       Linux)          test -e $DIR/include ;;
       GNU/kFreeBSD)   test -e $DIR/kern && test -e $DIR/conf/kmod.mk ;;
       *)              return 1 ;;
    esac
    return $?
}

case "${uname_s}" in
    Linux)
        header_pkg="linux-headers-$inst_kern"
        kernel="Linux"
    ;;
    GNU/kFreeBSD)
        header_pkg="kfreebsd-headers-$inst_kern"
        kernel="kFreeBSD"
    ;;
esac

#if [ -x /usr/lib/dkms/dkms_autoinstaller ]; then
    #exec /usr/lib/dkms/dkms_autoinstaller start $inst_kern > /dev/null
#fi

if ! _check_kernel_dir $inst_kern ; then
    echo "dkms: WARNING: $kernel headers are missing, which may explain the above failures." >&2
    echo "      install the $header_pkg package to fix this." >&2
    exit 0
fi


# If we reached this point, we can continue

# reconfigure (recompile) each -dkms package
# while read -ru 3 package
# do
#     # we cannot do it on this way because dpkg is locked:
#     ##dpkg-reconfigure -fnoninteractive -pcritical "$package"
#
#     if [[ -x "/var/lib/dpkg/info/${package}.postinst" ]] ; then
#         echo -e "\n\nRebuilding modules for: $package\n" 1>&2
#         "/var/lib/dpkg/info/${package}.postinst" configure || true
#     fi
# done 3<<< "$( COLUMNS=1000 dpkg -l | grep -E "^(h|i)i\s*.*[[:print:]]-dkms\s*" | awk '{print $2}' )"

# recompile each of these ones too
for _conf in /usr/src/*/dkms.conf
do
	if ! [[ -s "$_conf" ]] ; then
		continue
	fi

	_name="$( cat "$_conf" | grep "^PACKAGE_NAME=" | sed -e 's|PACKAGE_NAME="||g' -e 's|PACKAGE_NAME=||g' -e 's|".*$||g' | head -1 )"
	_version="$( cat "$_conf" | grep "^PACKAGE_VERSION=" | sed -e 's|PACKAGE_VERSION="||g' -e 's|PACKAGE_VERSION=||g' -e 's|".*$||g' | head -1 )"

	# build !
	if [[ -n "$_name" ]] && [[ -n "$_version" ]] ; then
		echo -e "\n\nRunning DKMS as: dkms install '$_name/$_version' -k '$inst_kern' \n" 1>&2
		dkms install "$_name/$_version" -k "$inst_kern" || true
	fi

done
