#!/usr/bin/perl -w

use warnings;
use strict;
use lib "/usr/local/sbin";
use lib "/usr/local/nagios/plugins";
use utils qw(%ERRORS);

my %hosts;
my $hosts_troubles;
my $TRAP_LOG = '/var/log/traps_format.log';
my $ret = $ERRORS{OK};

open (TRAPLOG,$TRAP_LOG) || die "no es pot obrir fitxer de traps del tripwire";

while (<TRAPLOG>) {
    chomp;
    if ($_=~/[a-zA-Z0-9\-]+\:\:\w+\.6818\.1\.0/ && $_!~/Test/) {
		my ($hostname, $violations, $violations_permit, $added, $removed, $changed) = 
			/TWReport\W+([a-zA-Z0-9\.]+)\W+\d+\W+V\:(\d+)\W+S\:(\d+)\W+A:(\d+)\W+R:(\d+)\W+C:(\d+)/;

		if ($hosts{$hostname}) {
			if ($violations eq 0) { 
				delete $hosts{$hostname};
			}
			else {
				 $hosts{$hostname} = $violations;
			}
		}
		else{
			$hosts{$hostname} = $violations if ($violations gt 0);
		}
		
    }
}
close(TRAPLOG);

foreach (sort(keys(%hosts))){
	$hosts_troubles = $hosts_troubles." ".$_.":".$hosts{$_};
}

if (defined $hosts_troubles){	
	print $hosts_troubles;
	$ret = $ERRORS{CRITICAL};
}
else{
	print "OK";
}

exit $ret;
