#! /usr/bin/perl -w
#


use strict;
use lib "/usr/lib/nagios/plugins";
use utils qw($TIMEOUT %ERRORS &print_revision &support);
use vars qw($PROGNAME);
use Getopt::Long;
use DateTime;
use vars qw($opt_V $opt_h $verbose $opt_w $opt_c $opt_H);

my $cachedir = "/var/cache/nagios3/tm_cache/";

$PROGNAME = "check_tm";
sub print_help ();
sub print_usage ();

$ENV{'PATH'}='';
$ENV{'BASH_ENV'}='';
$ENV{'ENV'}='';

Getopt::Long::Configure('bundling');
GetOptions
	("V"   => \$opt_V, "version"    => \$opt_V,
	 "h"   => \$opt_h, "help"       => \$opt_h,
	 "v" => \$verbose, "verbose"  => \$verbose,
	 "w=s" => \$opt_w, "warning=s"  => \$opt_w,
	 "c=s" => \$opt_c, "critical=s" => \$opt_c,
	 "H=s" => \$opt_H, "hostname=s" => \$opt_H);

if ($opt_V) {
	print_revision($PROGNAME,'1.0.0'); #'
	exit $ERRORS{'OK'};
}

if ($opt_h) {
	print_help();
	exit $ERRORS{'OK'};
}

$opt_H = shift unless ($opt_H);
print_usage() unless ($opt_H);
my $host = $1 if ($opt_H =~ m/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+|[a-zA-Z][-a-zA-Z0]+(\.[a-zA-Z][-a-zA-Z0]+)*)$/);
print_usage() unless ($host);

($opt_c) || ($opt_c = shift) || ($opt_c = 5);
my $critical = $1 if ($opt_c =~ /([0-9]+)/);

($opt_w) || ($opt_w = shift) || ($opt_w = 2);
my $warning = $1 if ($opt_w =~ /([0-9]+)/);

my $last_backup = `/usr/bin/snmpget -v 2c -c public $host .1.3.6.1.4.1.2021.8.1.101.1 2>/dev/null`;

if ($last_backup eq "") {
    if (-e $cachedir.$host) {
	open( my $fh, '<', $cachedir.$host );
	$last_backup  = <$fh>;
	chomp($last_backup);
	close $fh;
    } else {
	$last_backup=0;
    }
} else {
    my @test = split(/ /,$last_backup);
    $last_backup = $test[3];
}

my $lastdate = (DateTime->from_epoch( epoch => $last_backup ));
my $daysdiff = (DateTime->now())->delta_days($lastdate)->in_units('days');

printf("Last Backup Completed: %s - $daysdiff days ago\n",$lastdate->ymd('-'));
open( my $fh, '>', $cachedir.$host );
print $fh "$last_backup\n";
close $fh;

if ($daysdiff>$critical) {
	exit(2);
} elsif ($daysdiff>$warning) {
	exit(1);
} else {
	exit(0);
}


sub print_usage () {
	print "Usage: $PROGNAME -H <host> [-w <warn>] [-c <crit>]\n";
}

sub print_help () {
	print_revision($PROGNAME,'1.4.14');
	print "Copyright (c) 2012 Chris Beauchamp\n";
	print "\n";
	print_usage();
	print "\n";
	print "<warn> = Days at which a warning message will be generated.\n";
	print "<crit> = Days at which a critical message will be generated.\n\n";
	support();
}
