#!/bin/sh


message="Unable to execute check"
exit_code=3
version_information_collected=0
debian_kernel_packaged_installed=0

if [ $(dpkg -l | grep -c "linux-image-") -gt 0 ]; then
  debian_kernel_packaged_installed=1
fi

if [ $debian_kernel_packaged_installed -eq 1 ]; then
  RUNNING_KERNEL_RELEASE=$(uname --kernel-release)
  if [ $? -ne 0 ] || \
     [ -z "$RUNNING_KERNEL_RELEASE" ]; then
    message="Unable to determine release of running kernel"
  else
    RUNNING_DEBIAN_KERNEL_VERSION=$(uname -v | cut -d ' ' -f 4)
    if [ -z "$RUNNING_DEBIAN_KERNEL_VERSION" ]; then
      message="Unable to determine release of running kernel"
    else
      INSTALLED_DEBIAN_KERNEL_VERSION=$(dpkg-query --show --showformat='${Version}\n'  linux-image-$RUNNING_KERNEL_RELEASE)
      if [ $? -ne 0 ] || \
         [ -z "$RUNNING_KERNEL_RELEASE" ]; then
        message="Unable to determine version of installed Debian kernel"
      else
        version_information_collected=1
      fi
    fi
  fi
else
  message="Not covered by this check - no Debian kernel in use..."
  exit_code=0
fi

if [ $version_information_collected -eq 1 ]; then
  if [ "$RUNNING_DEBIAN_KERNEL_VERSION" = "$INSTALLED_DEBIAN_KERNEL_VERSION" ]; then
    message="OKAY: Kernel in version '$RUNNING_DEBIAN_KERNEL_VERSION' installed and in use"
    exit_code=0
  else
    message="Kernel in version '$RUNNING_DEBIAN_KERNEL_VERSION' in use, but '$INSTALLED_DEBIAN_KERNEL_VERSION' installed"
    exit_code=1
  fi
fi

echo $message
exit $exit_code
