#!/bin/sh
if [ "$1" = "-v" ]
then
	verbose=yup
	shift
fi

if [ "$1" = "-y" ]
then
	confirm_reboot=yes
	shift
fi

kernel_package=linux-image-server
if [ -n "$1" ]
then
	kernel_package="$1"	
fi

sed_exp='s/[^0-9]*\([0-9][0-9]*\).\([0-9][0-9]*\).\([0-9][0-9]*\)[.-]\([0-9][0-9]*\).*/\1 \2 \3 \4/'

sed_exp_5='s/[^0-9]*\([0-9][0-9]*\).\([0-9][0-9]*\).\([0-9][0-9]*\)[-.]\([0-9][0-9]*\)[-.]\([0-9][0-9]*\).*/\1 \2 \3 \4 \5/'

v=$(uname -r)
running_version=$(echo $v | sed "$sed_exp_5")
if [ "$v" = "$running_version" ]
then
	running_version=$(echo $v | sed "$sed_exp")
fi

if [ -f /etc/dpkg/origins/ubuntu ]
then
	installed_version=$(dpkg-query -W -f='${Version}\n' "$kernel_package" | sed "$sed_exp")
elif [ -d /var/lib/rpm ]
then
	installed_version=$(rpm -q --qf='%{Version}-%{Release}' "$kernel_package" | sed "$sed_exp_5")
else
	installed_version=$(dpkg-query -W -f='${Depends}\n' "$kernel_package" | sed "$sed_exp")
fi

if [ -z "$running_version" -o -z "$installed_version" ]
then
	echo cannot determine versions, aborting >&2
	exit 2
fi

if [ "$running_version" != "$installed_version" ]
then
	reboot_required=yes
fi
if [ -n "$verbose" ]
then
	echo "running kernel: $running_version"
	echo "installed:      $installed_version"
	[ -z "$reboot_required" ] || echo reboot required
fi

if [ -n "$reboot_required" -a -n "$confirm_reboot" ]
then
	/sbin/shutdown -r +5 "Reboot due to kernel update"
fi

[ -n "$reboot_required" ]
