#!/usr/bin/perl
use DBI;
use conf;
use CGI qw/:standard/;

#conf open_read
$conf_name="billing.conf";
$ctest=conf->var_read($conf_name);
$main_table=$ctest->{'mysql_tables.data'};
$css_path=$ctest->{'environment.css_path'};
$pkt_log=$ctest->{'mysql_tables.ipkt'};
$log_table=$ctest->{'mysql_tables.slow'};

@data=();
if(param())
    {
    $current_nip=param("nip");
    $dir=param("dir");
    }
$db_handle=DBI->connect("DBI:mysql:database=$ctest->{'mysql_connect.db_db'};host=$ctest->{'mysql_connect.db_host'}",$ctest->{'mysql_connect.db_user'},$ctest->{'mysql_connect.db_password'});
$uip=$db_handle->selectrow_array("SELECT inet_ntoa($current_nip);");
$timestamp=$db_handle->selectrow_array("SELECT now();");
if($dir eq "out")
    {
    $select_string="select prt_dst,proto,count(*) as count from $pkt_log where nip_src=$current_nip group by prt_dst,proto order by count desc limit 50;";
    $class='two';
    }
elsif($dir eq "in")
    {
    $select_string="select prt_src,proto,count(*) as count from $pkt_log where nip_dst=$current_nip group by prt_src,proto order by count desc limit 50;";
    $class='one';
    }
#HTML header
print"Content-type: text/html;charset=cp-1251;\n\n";
print"<html><head><title>$uip user stat</title>\n";
print"<link href=\"$css_path\" rel=\"stylesheet\" type=\"text/css\">\n";
print"</head>\n";
print"<body>\n";
print"<table border=0 width=100% height=100%><tr><td valign=center align=center>";
print"<table border=0 width=75%><tr><td align=center valign=top>";
print"<table border=0>\n";
$sth=$db_handle->prepare("$select_string");
$sth->execute();
$rows=0;
while(@data=$sth->fetchrow_array())
    {
    print"<tr>";
    $i=0;
    while(defined $data[$i]) {print"<td class=$class>$data[$i]</td>";if($class eq 'one'){$class='two';}else{$class='one';}$i++;}
    print"</tr>\n";
    $rows++;if($rows%10==0){print"</table></td>\n";if($rows!=50){print"<td align=center><table border=0>";}}
    @data=();
    }
$db_handle->do("INSERT INTO $log_table SET time_start=\"$timestamp\",time_stop=CURRENT_TIMESTAMP,users=(SELECT count(*) from $main_table),code='i';");
$db_handle->disconnect;
print"</table>\n";
print"</td></tr><tr><td align=left heigth=10><font color=white>$uip...$dir</font></td><tr></table>\n";
print"</body></html>\n";