#!/usr/bin/perl -w
use strict;

use Time::HiRes qw( usleep );
use IO::Handle;

my $interval = 500000;

my $clear = "\033[2J";
my $cursor_on = "\033?25h";
my $cursor_off = "\033?25l";

my $file = "/proc/net/dev";
my $lcd_dev = "/dev/lcd";

my $daemon = 1;
my $net_dev;

my $arg;
while (defined($arg = shift @ARGV)) {
	if ($arg eq '-f') {
		$daemon = 0;
	} elsif ($arg eq '-d') {
		$lcd_dev = shift @ARGV;
		if (!defined $lcd_dev) { usage(); }
	} else {
		$net_dev = $arg;
	}
}

if (!defined $net_dev) { usage(); }

my $prev_recv = -1;
my $prev_send = -1;

open LCD, ">$lcd_dev" or dienice("Could not open $lcd_dev");
LCD->autoflush(1);
print LCD "$clear$cursor_off";


#print LCD "\033[0;".(join ';', (16) x 8)."R";
#print LCD "\033[1;".(join ';', (24) x 8)."R";
#print LCD "\033[2;".(join ';', (28) x 8)."R";
#print LCD "\033[3;".(join ';', (30) x 8)."R";
#my @hb = ("\240","\000","\001","\002","\003","\377");


if ($daemon) {
	my $child = fork();
	if ($child != 0) { exit 0; } # exit parent
}

$SIG{'INT'} = \&handle_term;
$SIG{'TERM'} = \&handle_term;

for (;;) {
	my $up = 0;
	open DEV, $file || die "Error opening $file";
	while (<DEV>) {
		s/^\s*//o;
		if (/^$net_dev:/o) {
			$up = 1;
			my @values = split /[\s|\:]+/o;
			my $if = $values[0];
			my $recv = $values[1];
			my $send = $values[9];
			if ($prev_recv != -1 && $prev_send != -1) {
				my $recv_KBps = (1000000*($recv-$prev_recv)/$interval)/1024;
				my $send_KBps = (1000000*($send-$prev_send)/$interval)/1024;
				printf LCD "$clear<- %5.2f KB/s\n-> %5.2f KB/s", $recv_KBps, $send_KBps;

				#print LCD "$clear";
				#my $max_recv = 80;
				#my $max_send = 20;
				#print_bar($recv_KBps, $max_recv, 16);
				#print LCD "\n";
				#print_bar($send_KBps, $max_send, 16);
			}
			$prev_recv=$recv;
			$prev_send=$send;
		}
	}
	close DEV;
	if (!$up) {
		printf LCD "$clear$net_dev is down";
	}
	usleep($interval);
}

sub handle_term {
	print LCD "$clear$cursor_on"; # cursor on, clear, home
	close LCD;
	exit;
}

sub usage {
	dienice("Usage: netload [-f] <interface>");
}

sub dienice {
	print "$_[0]\n";
	exit(1);
}

#sub print_bar {
#	my ($val, $max, $width) = @_;
#	if ($val > $max) { $val = $max; }
#	my $full = int ($val * $width / $max);
#	my $part = $val % 5;
#	print LCD ($hb[5] x $full);
#	print LCD ($hb[$part]);
#}
