#!/usr/bin/perl
use DBI;
use CGI qw(:standard);
use tracker;
use tracker_cgi;


$| = 1;

print $tracker::tracker_header;
	
my $dbconn;
$dbconn = tracker::conndb() or cgi_die("database failure");
my $sth = $dbconn->prepare("select distinct switch from switch_ports");
$sth->execute or cgi_die("Database error:" . $dbconn->errstr);
while (@row = $sth->fetchrow_array)
        {
        push(@switches,{switch => $row[0]}) 
        }

foreach $hashref (@switches)
	{
	my $switch = $hashref->{"switch"};
	my $sth = $dbconn->prepare("select count(port) from switch_ports where switch = " . $dbconn->quote($switch) . ";");
	$sth->execute or cgi_die("Database error:" . $dbconn->errstr);
	( $hashref->{"ports_total"} ) = $sth->fetchrow_array;
	$sth = $dbconn->prepare("select count(port) from switch_ports where switch = " . $dbconn->quote($switch) . " and" .
				" adminstatus = 1;");
	$sth->execute or cgi_die("Database error:" . $dbconn->errstr);
	( $hashref->{"ports_inuse"} ) = $sth->fetchrow_array;
	$hashref->{"inuse_ratio"} = $hashref->{"ports_inuse"} / $hashref->{"ports_total"}
	}
$sth->finish;
$dbconn->disconnect;

@sorted = sort compare @switches;
print "<table border=1><tr><td>switch</td><td>% ports in use</td><td>used/total</td></tr>\n";
	
foreach $hashref (@sorted)
	{
	print "<tr><td>", $hashref->{"switch"}, "</td><td>", int($hashref->{"inuse_ratio"}*100), 
		"</td><td>", $hashref->{"ports_inuse"},"/",$hashref->{"ports_total"},"</td></tr>\n"
	}
	
print "</table>";
tracker::tracker_end;

sub compare
	{
	if ( $b->{"inuse_ratio"} == $a->{"inuse_ratio"} ) 
		{ return $b->{"ports_total"} <=> $a->{"ports_total"} }
	else
		{ return $b->{"inuse_ratio"} <=> $a->{"inuse_ratio"} }
	}
	

