# rsnapshot backup tool log parsing script
# Hayden Lau, July 2016

use strict;
my $Debug = $ENV{'LOGWATCH_DEBUG'} || 0;
my $Detail = $ENV{'LOGWATCH_DETAIL_LEVEL'} || 0;
my %Error;
my %Warning;
my %Started;
my %Successful;
my %OtherList;

while (defined(my $ThisLine = <STDIN>)) {
   chomp($ThisLine);
   if ($Debug) {
      print "$ThisLine\n";
   }
   if ($ThisLine =~ /ERROR: (\N+)/) {
      $Error{$1}++;
   } elsif ($ThisLine =~ /WARNING: (\N+)/) {
      $Warning{$1}++;
   } elsif ($ThisLine =~ / (\S+): started/) {
      $Started{$1}++;
   } elsif ($ThisLine =~ / (\S+): completed successfully/) {
      $Successful{$1}++;
   } else {
      $OtherList{$ThisLine}++;
   }
}

if (keys %Error) {
   print "ERRORS:\n";
   foreach my $line (sort {$a cmp $b} keys %Error) {
      print "    $line: $Error{$line} Time(s)\n";
   }
}

if (keys %Warning) {
   print "Warnings:\n";
   foreach my $line (sort {$a cmp $b} keys %Warning) {
      print "    $line: $Warning{$line} Time(s)\n";
   }
}

if (($Detail > 5) and keys %Started) {
   print "Started:\n";
   foreach my $retain (sort { $Started{$b} <=> $Started{$a} } keys %Started) {
      print "    $retain: $Started{$retain} Time(s)\n";
   }
}

if ($Detail and keys %Successful) {
   print "Completed Successfully:\n";
   foreach my $retain (sort { $Successful{$b} <=> $Successful{$a} } keys %Successful) {
      print "    $retain: $Successful{$retain} Time(s)\n";
   }
}

if (keys %OtherList) {
   print "\n**Unmatched Entries**\n";
   foreach my $line (sort {$a cmp $b} keys %OtherList) {
      print "    $line: $OtherList{$line} Time(s)\n";
   }
}

exit(0);
