#!/usr/bin/perl

if ($#ARGV >= 0) {
    @logfiles = @ARGV;
} else {
    @logfiles = `ls /var/log/iseg2dim* | sort -r`;
}


foreach $l (@logfiles) {

    print "analyzing $l\n";

    open LOGFILE, $l;

    $line1 = ( "======================================================".
	       "======================================================" );
	
    $line2 = ( "------------------------------------------------------".
	       "------------------------------------------------------" );

    while(<LOGFILE>) {
	
	if (/(\w+\s+\w+\s+[0-9:]+).*iseg2dim\.bus\d\.mod(\d\d): (.*)$/) {
	    
	    $date = $1;
	    $mod = $2;
	    $msg = $3;
	    
	    $state{$mod} = 'idle' unless exists $state{$mod};
	    
	    if ( $state{$mod} ne 'idle' ) {
		$logmsg{$mod} .= "$date - $msg\n";
	    }
	    
	    if ( $msg =~ /(\d*) of (\d*) pkts pending/ ) {

		$npend = $1;
		$nexp = $2;
		
		if (scalar keys %logmsg == 0 ) {
		    print "$line1\n";
		    print "Timeout: $date\n";
		    print "$line2\n\n";		
		}
		
		if ( $state{$mod} eq 'idle' ) {
		    $logmsg{$mod} .= "$date - $msg\n";
		}
		
		$state{$mod} = 'pending';
		
		
	    } elsif ($msg =~ /recovered from timeout/) {
		
		if ( $state{$mod} eq '1-pktloss' ) {
		    print "mod$mod: recovered from PKTLOSS ($npend of $nexp)\n";

		} elsif ( $state{$mod} eq '1-resend' ) {
		    print "mod$mod: recovered after RESENDING ($npend of $nexp)\n";
		} elsif ( $state{$mod} eq '3-ignore' ) {
		    print "mod$mod: recovered after IGNORE ($npend of $nexp)\n";		    
		    #print $logmsg{$mod};
		    #print "\n";
		} else {
		    print "mod$mod: unclassified error:\n";
		    print $logmsg{$mod};
		    print "\n";
		}
		
		$state{$mod} = 'idle';
		delete $logmsg{$mod};
		
		if ( scalar keys %logmsg  == 0 ) {
		    print "fully recovered: $date\n\n";
		} 

	    } elsif ($msg =~ /mark module as dead/) {

		print "mod$mod: UNRECOVERED error:\n";
		print $logmsg{$mod};
		print "\n";
		
		$state{$mod} = 'idle';
		delete $logmsg{$mod};
		
		if ( scalar keys %logmsg  == 0 ) {
		    print "fully recovered: $date\n\n";
		} 
		
	    } elsif ($msg =~ /1st timeout: possible packet loss/) {
		$state{$mod} = '1-pktloss';
		
	    } elsif ($msg =~ /1st timeout: resend message/) {
		$state{$mod} = '1-resend';
		
	    } elsif ($msg =~ /2nd timeout -> pause sending/) {
		$state{$mod} = '2-pause';
		
	    } elsif ($msg =~ /3rd timeout -> ignore outstanding packets/) {
		$state{$mod} = '3-ignore';
		
	    } else {
		#$state{$mod} = 'unknown';
	    }
	    
	    #print $state{$mod}."\t - $date  mod$mod: $msg\n";
	}
    }
}

close LOGFILE;
