#!/usr/bin/perl -w

use strict;
use warnings;
use Scalar::Util qw(looks_like_number);
use Getopt::Long;
use Data::Dumper;

# If no arguments given, then we use defaults from script.
my ($ntpdata, $message, $status, $exitcode);
my $ntpserver = "ntp.bit.nl";
my $warning   = 1.5;
my $critical  = 2.0;
my $offset    = "UNKNOWN";

GetOptions ("H=s"  => \$ntpserver,
            "w=s"  => \$warning,
            "c=s"  => \$critical,
           ) or die("Error in command line arguments\n");

$ntpdata = `w32tm /stripchart /computer:$ntpserver /samples:1 /dataonly` or die ("Error in calling w32tm binary");

my @lines = grep /\S/, split /\n/, $ntpdata;
if (defined($lines[3])) {
    $offset = substr $lines[3], 11, -1 . "\n";
} else {
    if (defined($lines[0])) {
        $offset = $lines[0];
    } else {
        $offset = "UNPARSABLE DATA";
    }
}

$status   = "OK";
$exitcode = 0;
$message  = " - NTP Offset $offset (SVR:$ntpserver WARN:$warning, CRIT:$critical)\n";

if (not looks_like_number($offset)) {
    $status   = "WARNING";
    $exitcode = 1;
} elsif ($offset > $critical) {
    $status   = "CRITICAL";
    $exitcode = 2;
} elsif ($offset > $warning) {
    $status   = "WARNING";
    $exitcode = 1;
}

print $status . $message;
exit($exitcode);

