#!/usr/bin/perl
#
# NRPE Script to report amanda backup errors found in the trace logs.
#
# Developed by: Global Research Network Operations Center (GRNOC)
#
# Example Usage: perl check_amanda.pl PoolA   

use strict;
use warnings;

my $pool = $ARGV[0] || die("usage: perl check_amanda.pl <backup Pool> \n");

my %NAGIOS_API_ECODES = ( 'OK' => 0, 'WARNING' => 1, 'CRITICAL' => 2, 'UNKNOWN' => 3 ); 
my $_intDegCount = 0;
my $LH = "/etc/amanda/$pool/log";


opendir(DIR, $LH);
my @files = readdir(DIR);
closedir(DIR);

my $log;

#sort files so that most recent log is last
my @sortedFiles = sort @files;
foreach my $file (@sortedFiles) {
	next if ($file eq "." || $file eq "..");

	if ($file =~ m/log.*/ && $file ne "oldlog" && !($file =~ m/error/)){
		$log = $LH."/".$file;
	}	

}

open(DATA, $log) || die("Can't open $log");
my @lines = <DATA>;
close(DATA);



my $error;

foreach my $x (@lines){
        if ($x =~ m/ERROR/ || $x =~ m/FAIL\s\w*\s(.*edu )/){
		#strip trailing newline
		chomp($x);
		if ($1){
			if ($error =~ /$1/){
				#ignore multiple entries for single host
			}else{
				$error.=" FAILED filesystem on ".$1." -";
			}
		}else{ 
			$error.=" ".$x." -";	
		}
		$_intDegCount++;		
	
        }else{

        }
}

chop($error);


if ($_intDegCount > 0 ) {
	print "There was a problem with the following ($log): ".$error."\n";

        exit $NAGIOS_API_ECODES{CRITICAL};
} else {
        print "Backup $pool: All machines backed up.";
         exit $NAGIOS_API_ECODES{OK};
}



