#!/bin/sh

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

uname_s=$(uname -s)

_get_kernel_dir() {
    KVER=$1
    DIR="/lib/modules/$KVER/build"
    echo "$DIR"
}

_check_kernel_dir() {
    DIR=$(_get_kernel_dir "$1")
    test -e "$DIR/include"
}

header_pkg="linux-headers-$inst_kern"
kernel="Linux"

case $0 in *header_postinst.d*)
    # unbuild all autoinstalled modules for this kernel to ensure they get
    # rebuilt against the updated headers by the next autoinstall below
    for mod_ver in $(dkms status -k "$inst_kern" 2>/dev/null | grep ': installed' | cut -d, -f1 | sort -u)
    do
        dkms_conf="/var/lib/dkms/$mod_ver/source/dkms.conf"
        autoinstall=$(bash -c 'AUTOINSTALL=; . "'"$dkms_conf"'" >/dev/null 2>&1; echo $AUTOINSTALL')
        test -n "$autoinstall" || continue
        dkms unbuild -k "$inst_kern" "$mod_ver"
    done
    ;;
esac

if [ -x /usr/lib/dkms/dkms_autoinstaller ]; then
    exec /usr/lib/dkms/dkms_autoinstaller start "$inst_kern"
fi

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