#! /usr/bin/perl
use CGI;
use GD;
use DBI;
use lib '../include';
use nms;
my $cgi = CGI->new;

my $dbh = nms::db_connect();

GD::Image->trueColor(1);
$img = GD::Image->new('snmp-bg.png');

my $blk = $img->colorResolve(0, 0, 0);

for my $y (42..236) {
	my $i = 2.0 * ($y - 236.0) / (42.0 - 237.0);
	my $clr = get_color($i);
	
	$img->filledRectangle(32,$y,53,$y+1,$clr);
}

my $q = $dbh->prepare('select * from switches natural join placements natural left join
( select switch,sum(bytes_in)/count(*) as
bytes_in,sum(bytes_out)/count(*) as bytes_out from get_datarate() group
by switch ) t1 where ip<>\'127.0.0.1\'');
$q->execute();
while (my $ref = $q->fetchrow_hashref()) {

	# for now:
	# 100kbit/port = all green
	# 1gbit/port = all red
	
	my $clr;

	if (defined($ref->{'bytes_in'})) {
		my $intensity = 0.0;
		my $traffic = 4.0 * $ref->{'bytes_in'} + $ref->{'bytes_out'};  # average and convert to bits (should be about the same in practice)

		my $max = 20_000_000.0;   # 10mbit
		my $min =    100_000.0;   # 100kbit
		if ($traffic >= $min) {
			$intensity = 2.0 * (log($traffic / $min) / log(10)) / (log($max / $min) / log(10));
			$intensity = 2.0 if ($intensity > 2.0);
		}       
		$clr = get_color($intensity);
	} else {
		$clr = $img->colorResolve(0, 0, 255);
	}
	
	$ref->{'placement'} =~ /\((\d+),(\d+)\),\((\d+),(\d+)\)/;
	$img->filledRectangle($3,$4,$1,$2,$clr);
	$img->rectangle($3,$4,$1,$2,$blk);
        $img->stringUp(gdSmallFont,$3,$2-3,$ref->{'sysname'},$blk);
}
$dbh->disconnect;

print $cgi->header(-type=>'image/png');
print $img->png;

sub get_color {
	my $intensity = shift;
	my $gamma = 1.0/1.90;
	if ($intensity > 1.0) {
		return $img->colorResolve(255.0, 255.0 * ((2.0 - $intensity) ** $gamma), 0);
	} else {
		return $img->colorResolve(255.0 * ($intensity ** $gamma), 255, 0);
	}
}
