#!/usr/bin/perl -w

# Quick hack to monitor some stuff on Spike / Waider, May/June 2000

use Tk;
use POSIX qw( strftime );

my $lastcheck = time;
my $lastin;
my $lastout;
my $pin = 0;
my $pout = 0;
my $pb = 0;
my $main = new MainWindow;

$netdev = shift;
die "Specify a network device to monitor" unless $netdev;

$main->Label(-wrap=>0,
			 -fg=>'Green', -bg=>'black',
			 -textvariable => \$message1,
			 -font => 'fixed',
			 -width=>80, -height=>1)->pack;

$main->Label(-wrap=>0,
			 -fg=>'Green', -bg=>'black',
			 -textvariable => \$message2,
			 -font => 'fixed',
			 -width=>80, -height=>1)->pack;

$main->after(1000, \&newdata);

MainLoop;

sub newdata {
  $message1 = uptime();
  $message2 = pppstats();
  $main->after(1000, \&newdata);
}

sub uptime {
  my $foo = `uptime`;
  chomp( $foo );
  $foo;
}

sub pppstats {
  my $now = time;
  my @now = localtime;
  if ( open( PPP, "</proc/net/dev" )) {
	my @lines = grep /$netdev/, <PPP>;
	close( PPP );
	push @lines, "rubbish"; # in case the interface is down.
	my ( $in, $out ) = $lines[ 0 ] =~
	  m|^[^0-9]+\d+:\s*(\d+)\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+(\d+)\s+|;

	$in = $in * 8;
	$out = $out * 8;

	if ( !defined( $lastin )) {
	  $lastin = $in;
	}

	if ( !defined( $lastout )) {
	  $lastout = $out;
	}

	my $din = $in - $lastin;
	my $dout = $out - $lastout;
	$lastin = $in;
	$lastout = $out;

	my ( $irate, $orate ) = ( 0, 0 );
	if ( $now - $lastcheck > 0 ) {
	  $irate = $din / ( $now - $lastcheck );
	  $orate = $dout / ( $now - $lastcheck );
	} else {
	  $irate = 0;
	  $orate = 0;
	}

	if ( $irate > $pin ) {
	  $pin = $irate;
	}

	if ( $orate > $pout ) {
	  $pout = $orate;
	}

	if ( $orate + $irate > $pb ) {
	  $pb = $orate + $irate;
	}

	$lastcheck = $now;
#	$main->configure(-title=>sprintf("[peak: %5d/%5d %5d]",
#									 $pin, $pout, $pb));
	$main->iconname( sprintf("[%5d/%5d %3d]", $irate, $orate,
							 int(( $irate+$orate ) * 100 /131072 + 0.5 )));
	strftime("%H:%M:%S", @now) .
	  sprintf( " in: %5d b/s out: %5d b/s [peak: %5d/%5d %5d]",
			   $irate, $orate, $pin, $pout, $pb );
  } else {
	strftime( "%H:%M:%S", @now ) . "$!";
  }
}
