#!/usr/bin/perl -w

#Usage:
# ./snmp_plot.pl <interface> [<field to plot> [<field to plot> [...]]] | gnuplot

#$Id$

use strict;

my $LOGBASE = "./snmpwalk";
my @INTERFACES = ("137.164.23.195", "128.125.251.102");

my $ip= $ARGV[0];

my @whatplot;
for (my $i=0; ; ++$i) {
    if (defined ($ARGV[$i+1])) {
	push @whatplot, $ARGV[$i+1];
    }
    else {
	last;
    }
}

my $AVG_TIME = (10*60); #in seconds

my @NAMES = (
	     "ifAdminStatus",
	     "ifOperStatus",
	     "ifInOctets", 
	     "ifInUcastPkts",
	     "ifInNUcastPkts",
	     "ifInDiscards",
	     "ifInErrors",
	     "ifInUnknownProtos",
	     "ifOutOctets",
	     "ifOutUcastPkts",
	     "ifOutNUcastPkts",
	     "ifOutErrors",
	     "ifOutQLen"
	     );
my %values;
my $i = 0;
foreach (@NAMES) {
    $values{$_} = $i;
    ++$i;
}

foreach my $val (@whatplot) {
    die "Unknown name: $val" 
	unless defined $values{$val};
}

print <<EOF;
set term post color solid
set out "snmpwalk-$ip.ps"
set title 'snmp data for $ip'
set xlabel 'Date/Time'
set ylabel 'Rate'
set log y
set xdata time
set timefmt '%s'
set format x "%m/%d"
set style data line
set key bottom right
EOF
    ;
    
print "plot ";
foreach my $val (@whatplot) {
	my $fld_dex = $values{$val} + 1; #first one is time
	my $fld_acc = 0;
	my $fld_prev;
	my $ts_acc = 0;
	my $ts_prev;
	my $firstline = 1;
	
	my $input = "$LOGBASE.$ip";
	my $output = "tmp.snmpwalk.$ip.$val";
	open (INP, "<$input")
	    or die "cannot open $input: $!";
	open (OUT, ">$output")
	    or die "cannot open $output: $!";
	print "'$output' u 1:2 t'$val'";
	if ($val ne $whatplot[$#whatplot]) {
	    print ", ";
	}
	my @array; 
	while (<INP>) {
	    chomp;
	    push @array, "$_\n";

	    my @flds = split / /;
	    
	    next if $#flds != @NAMES;
	    
	    #next if $flds[2] != 1;

	    my $ts = $flds[0];
	    my $fld= $flds[$fld_dex];
	    my $delta_fld = 0;
	    my $delta_ts = 0;
	    if ($fld eq '-') {
		goto newwin;
	    }
	    
	    if ($firstline) {
		$fld_prev = $fld;
		$ts_prev = $ts;
		$firstline = 0;
		next;
	    }

	    $delta_ts = $ts - $ts_prev;
	    next 
		if ($delta_ts < 2); #make sure time grows at least by 2 sec

	    $ts_prev = $ts;

	    #our field values should only increase, so
	    $delta_fld = $fld - $fld_prev;
	    if ($delta_fld < 0) {
		$delta_fld += 2**32; #assume 32-bit overflow
	    }
	    $fld_prev = $fld;
	    
	    
	    
	    if ($ts_acc + $delta_ts < $AVG_TIME) {
		$fld_acc += $delta_fld;
		$ts_acc += $delta_ts;
		#average within the window
		next;
	    }
	  newwin:
	    #start of the new window
	    if ($ts_acc != 0) {
		my $rate = $fld_acc/$ts_acc;
		my $tsmid= ($ts - $delta_ts - $ts_acc/2);
#		if ( $rate > 1e+06 ) {
#		    pop @array;
#		    print STDERR " @array";
#		    print STDERR "____$rate $tsmid\n";
#		}
		printf OUT "%d %g\n", int($tsmid), $rate;
	    }
	    $fld_acc = 0;
	    $ts_acc = 0;
	    @array=();
	    push @array, "$_\n";
	}
	close (INP);
    }

exit 0;
