#!/usr/bin/perl
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# Thomas Karlsson nagios at relea se

use warnings;
use strict;
use Getopt::Long;

my $version = "1.01";
my $warningthreshold = 87000;		# 24 hours + 600 seconds as default values
my $criticalthreshold = 173400;		# 48 hours + 600 seconds as default values
my $debuglevel = 0;			# Default debug level
my %options;				# A global variable
my %RETCODES = ('OK' => 0, 'WARNING' => 1, 'CRITICAL' => 2, 'UNKNOWN' => 3);	# Just define Nagios standard error codes

sub showhelp() {
	print <<EOL;
Checks the files in a directory, extracts the latest one to see that its not too old.

Version: $version
Usage:	$0 [options] filenames

Options:
	-w		Warning threshold in seconds
	-c		Critical threshold in seconds
	-v		Verbose output 0,1,2,3
	-V		Version

Examples:
	$0 -w 3600 -c 7200 /database/customers.*
	$0 /database/export.all.sql
EOL
	exit $RETCODES{'UNKNOWN'};			# Return unknown
}

sub debugprint ($$) {					# Allow two arguments
	my $level = shift;				# Get first argument
	my $msg = shift;				# Get second argument
	my $ltime = localtime(time());			# Get current time
	chomp($msg);					# Remove ENTER
	if ( $level le $debuglevel ) {			# Check if we're going to print this
		print "$ltime:$msg\n";				# Print it
	}
}

GetOptions(\%options, 'w=i', 'c=i','v+','h','V');		# Get options from the user
my $filenames = shift;					# The last argument are the filenames

if ( defined($options{'V'}) ) { print "Version $version\n"; exit 0; }

$debuglevel = $options{'v'} if defined($options{'v'});	# Set the debug level from the user input

unless ( defined($filenames) ) { showhelp(); }		# If no filename has been defined, lets show some help

$warningthreshold = $options{'w'} if defined($options{'w'}); # Set user defined values if they exist
debugprint(2,"It shows a warning if the file is more than $warningthreshold seconds old\n");
$criticalthreshold = $options{'c'}if defined($options{'c'}); # Set user defined values if they exist
debugprint(2,"It shows critical if the file is more than $criticalthreshold seconds old\n");

my @files = glob($filenames);				# Get all matching files
my %filetable;						# Aah, some global variables
my $latestbackup;					# Whohoo, another one

foreach my $singlefile ( @files ) {			# Loop through all files
	debugprint(3,"Indexing file/directory $singlefile\n");
	if ( -f  $singlefile  ) {				# Make sure its a file
		my @filedata = stat($singlefile);		# Get metadata of that file
		my $createdtime = $filedata[9]; 		# Get the create time
		my $readabledate = localtime($createdtime);	# Get a readable string from unixtime
		debugprint(3,"$singlefile is a file and was mad $readabledate ($createdtime)\n");
		$filetable{$createdtime} = $singlefile;		# Put filename and creation date in a hash
	} else {
		print "UNKNOWN: There were only directories in $singlefile i.e no files found.\n";
		exit $RETCODES{'UNKNOWN'};						# Returning an UNKNOWN error
	}
}
foreach my $onefile ( sort {$a <=> $b} keys(%filetable) ) {			# Just loop through each variable to get the last one
	debugprint (10,"Sorted file $onefile and $filetable{$onefile}\n");
	$latestbackup = $onefile;				# Always save the date, because the last loop we will have the latest date
}
		
my $workingfile = $filetable{$latestbackup};                    # Put the latest file in a variable
$workingfile =~ s/.*\///;					# Strip everything before the last / i.e remove the full path
debugprint(1,"$workingfile is the latest one\n");		# Print out which I think is the latest

my $warning = $latestbackup + $warningthreshold;	# Add maxage seconds to the file creation time.
my $critical = $latestbackup + $criticalthreshold;	# Add maxage seconds to the file creation time.
my $currenttime = time();				# Get current time
if ( time() > $warning ) {			# Check if current time is greater than the calculated value WARNING CHECK
	if ( time() > $critical ) {		# Check if its critical
		print "CRITICAL: $workingfile is too old\n";
		exit $RETCODES{'CRITICAL'};	# Return CRITICAL
	} else {
		print "WARNING: $workingfile is getting too old\n";	
		exit $RETCODES{'WARNING'};	# Return WARNING
	}
} else {					# Nope, it wasn't
	print "OK: $workingfile is OK\n";
	exit $RETCODES{'OK'};			# Return OK
}
