#! /usr/bin/perl -w

# Waider 26/09/2000
package Monitor::ifup;

use Monitor;
@ISA = "Monitor";

sub newdata {
  my $mon = shift;
  my $text = $mon->{'text'};
  my $lasttime = $mon->{'lastrun'};
  my $ifsr = $mon->{'ifs'};

  if ( defined( $ifsr )) {
	%ifs = %{$ifsr};
  } else {
	%ifs = ();
  }

  if ( open( IFLIST, "</proc/net/dev" )) {
	my @ifs = <IFLIST>;
	close( IFLIST );

	my ( $ifw, $rxw, $txw ) = ( 0, 0, 0 );

	# discard first two lines
	shift @ifs;
	shift @ifs;

	for my $ifl (@ifs) {
	  $ifl =~ s/[: ]+/ /g;
	  $ifl =~ s/^\s+//;

	  # this is what we're parsing
      # lo 1108793 15899 0 0 0 0 0 0 1108793 15899 0 0 0 0 0 0

	  my ( $ifname, $rxbytes, undef, undef, undef, undef, undef, undef,
		   undef, $txbytes, @rest ) = split(/\s+/, $ifl );
	  my ( $rxrate, $txrate ) = ( 0, 0 );

	  if ( $ifs{ $ifname }) {
		my ( $orx, $otx, @rates ) = split( "\0", $ifs{$ifname});
		$orx ||= $rxbytes;
		$ory ||= $txbytes;

		# calculate instantaneous change FIXME merge old data
		if ( defined( $lasttime ) && $lasttime != time ) {
		  $rxrate = int(( $rxbytes - $orx ) / ( time - $lasttime ));
		  $txrate = int(( $txbytes - $otx ) / ( time - $lasttime ));
		}
	  }

	  $ifs{$ifname} = "$rxbytes\0$txbytes\0$rxrate\0$txrate";

	  if ( length( $ifname ) > $ifw ) {
		$ifw = length( $ifname );
	  }
	  if ( length( $rxrate ) > $rxw ) {
		$rxw = length( $rxrate );
	  }
	  if ( length( $txrate ) > $txw ) {
		$txw = length( $txrate ) ;
	  }
	}

	my $fmt = "%${ifw}s|%${rxw}s/%${txw}s\n";

	$text = "";
	for my $ifn ( sort keys %ifs ) {
	  $text .= sprintf( $fmt, $ifn, (split( "\0", $ifs{$ifn}))[2,3]);
	}

	# stash the values
	$mon->{'ifs'} = \%ifs;

  } else {
	$text = $!;
  }

  $text;
}
