#!/usr/bin/perl -w

#
# This script compares the version of the currently running kernel 
# with the one defined in the Quattor profile for the current host
# If they are different, a warning is returned
# 
# Later: also compare GRUB config; if the kernel version in the Quattor
#

use strict;
use Getopt::Long;

my $verbose=0;
my $help;
my $hostname;

my $TIMEOUT = 20;

GetOptions("help" => \$help,
           "hostname|H:s" => \$hostname, 
           "timeout|t:i" => \$TIMEOUT,
           "verbose|v+" => \$verbose );

my %ERRORS=(OK=>0,
            WARNING=>1,
            CRITICAL=>2,
            UNKNOWN=>3,
            DEPENDENT=>4);


my $KERNEL_VERSION_PATH = '/system/kernel/version';
my $NCM_QUERY = "/usr/bin/ncm-query";
( -x $NCM_QUERY ) or die "$NCM_QUERY: $!\n";

my $result = $ERRORS{"UNKNOWN"};
my $message = "";

# Just in case of problems, let's not hang Nagios
$SIG{'ALRM'} = sub {
     print ("ERROR: No response from probe (alarm timeout)\n");
     exit $ERRORS{"UNKNOWN"};
};

alarm($TIMEOUT);

##############################################################################
# compare kernel versions
#

my $running_kv = &get_running_kernel_version;
my $configured_kv = &get_configured_kernel_version;
if ( ! defined $running_kv ) {
    $message = "Failed to determine running kernel";
}
elsif ( ! defined $configured_kv ) {
    $message = "Failed to determine configured kernel";
}
else {
    # both versions are defined; compare them
    if ( $running_kv eq $configured_kv ) {
        $result = $ERRORS{"OK"};
    }
    else {
        $result = $ERRORS{"WARNING"};
        $message = "Running kernel $running_kv differs from configured version $configured_kv";
    }
}

alarm(0);


# Write output and return exit code;
if ( $result == $ERRORS{"OK"} ) {
    $message = "OK: kernel version = $running_kv";
}

print "$message\n";
exit($result);




# determine the version of the kernel configured in the Quattor profile
# return: string with kernel version or undef
sub get_configured_kernel_version {
    my $cmd = 'sudo ' . $NCM_QUERY . ' ' . $KERNEL_VERSION_PATH;
    my @output = `$cmd`;
    if ( $? == 0 ) {
        if ( $output[@output-1] =~ /^\$.*\'(.+)\'$/ ) {
            return $1;
        }
    }
    return undef;
}


# determine the version of the running kernel
# return: string with kernel version or undef
sub get_running_kernel_version {
    my $cmd = 'uname -r';
    my $version = `$cmd`;
    if ( $? == 0 ) {
        chomp $version;
        return $version;
    }
    else {
        return undef;
    }
}

