#!/usr/bin/perl -w

package UserapHtml;

use strict;
use UserapCommon;
my $O_F= $HTMLOUTFILE;

my $COUNTERSTATFILE="$DATADIR/tc_dump.xml";
my $USERAPSTATFILE="$DATADIR/tc_update.xml";

my $nicks;

sub jednotky {
    (my $cislo) = @_;
    my $retval = "";
    my $cifra = 0;
    $cifra = int( $cislo / (1024*1024*1024*1024));
    if ($cifra) { 
	$retval .= sprintf ("<font color=blue> %.3f</font>TB", ($cislo / (1024*1024*1024*1024)));
    } else {
	$cislo = $cislo % (1024*1024*1024*1024);
	$cifra = int ( $cislo / (1024*1024*1024));
	if ($cifra) {
	    $retval .= sprintf ("<font color=red> %.3f</font>GB", ($cislo / (1024*1024*1024)));
	} else {
    	    $cislo = $cislo % (1024*1024*1024);
	    $cifra = int ( $cislo / (1024*1024));
	    if ($cifra) {
		$retval .= sprintf ("<font color=green> %.3f</font>MB", ($cislo / (1024*1024)));
	    } else {
		$cislo = $cislo % (1024*1024);
		$retval .= int ( $cislo / (1024)) ."kB ";
	    }
	}
    }
    return $retval;
}


sub print_general_data {
    print " general";
    print OF "<h2>Obecne informace</h2>\n";
    print OF "<p class='note'>\n";
    if (defined($UVERS)) {
	print OF "userapd version: $UVERS <br>\n";
    }
}

sub print_config_table {
    my ($face,$data) = @_;
    
    my $l1="-"; my $l2="-";my $p0="-";my $p1="-";my $p2="-";
    if (${$data}{type} eq "userap") {
        $l1 = jednotky(${$data}{limit1});
        $l2 = jednotky(${$data}{limit2});
        $p0 = ${$data}{penalty0};
        $p1 = ${$data}{penalty1};
        $p2 = ${$data}{penalty2};
    } 
    print OF "<td>$face</td><td>${$data}{type}</td><td>${$data}{rate}/${$data}{speed}</td><td>$p0/$p1/$p2</td><td>$l1 / $l2</td>\n";
}

sub print_config_data {
    my ($conf_data) = @_;
    print " config";
    print OF "<h2>Nastaveni rozhrani</h2>\n";
    print OF "<table title='Interface' style='text-align:center'>\n";
    print OF "<tr><th>dev</th><th>typ</th><th>down <br>rate / ceil</th>
    <th>down<br>pen. (0/1/2)</th><th>down <br>limit1 / limit2</th>
    <th>imq</th><th>typ</th><th>up <br>rate / ceil</th><th>up<br>pen. (0/1/2)</th>
    <th>up<br>limit1 / limit2</th></tr>\n";

    while (my ($face,$data) = each (%{$conf_data})) {
	#print "$face ".$data->{iface}." \n";
	if ($face =~ /imq/ ) { next; }
	print_config_table($face,$data);
        if ($data->{queues} ne $face ) {
    	    print_config_table ($data->{queues},$conf_data->{"$data->{queues}"});
	}
	print OF "</tr><tr>\n";
		
    }
    print OF "</table>\n";
}

sub print_iface_stats {
    my ($conf,$rc,$if_total,$sum_total,$sum_hour) = @_;
    print " iface_stats";
    print OF "<h2>Prenesena data podle rozhrani</h2>\n";
    #vypis statistik pro jednotilive interfacy
    my @pole =();
    while (my ($id,$data) = each (%{$sum_total})) {
	push @pole, $id;
    }
    @pole = sort {$a <=> $b} @pole;

    while (my ($pif, $data) = each (%{$conf})) {
	if ($conf->{$pif}->{type} ne "userap") {next;}
	if ($pif =~ /imq/ ) {next;}
	my $namedescr = $data->{"descr"} ?  $data->{"descr"} : " ";
	print OF "<h3>$pif - $namedescr</h3>\n";
	print OF "<table title='Users'  style='text-align:center' width='520'>\n";
	print OF "<tr><th>ID</th><th style='width:5em'>nick</th><th>traffic <br> DOWN/UP [B]</th><th>omezeni <br>D/U [kbit/s]</th><th>celkem <br>[B]</th><th>za 1h <br>[B]</th></tr>\n";
	my $count=0;
	my $default_row = "";
	foreach (@pole) {
	    my $iid = $_;
	    if (!exists($rc->{"$iid:$pif"})) {
		#print "! $iid:$pif\n";
	        next;
	    } 
	    my $upf = $data->{queues};
	    #print "$iid $pif $upf \n";
	    my (undef,$icdwn) = split (":", $rc->{"$iid:$pif"});
	    my (undef,$icup) = split (":", $rc->{"$iid:$upf"});
	    my $tup="";my $tdwn="";
	    $tdwn = $if_total->{$pif}->{$iid};
	    $tup = $if_total->{$data->{queues}}->{$iid};
	    my $nick="neznamy";
	    if (exists($nicks->{"$iid"})) {
		$nick=$nicks->{"$iid"};
	    }
	    my $diff_traf = $sum_hour->{"$iid"};
	    my $total_traf = $sum_total->{"$iid"};
	    $total_traf=jednotky($total_traf);
	    $diff_traf=jednotky($diff_traf);
	    $count++;
	    $tdwn=jednotky($tdwn);
	    $tup=jednotky($tup);
	    if ($iid == $DEFAULT_CLASS) {
		$default_row = "<tr><td>$iid</td><td>$nick</td><td>$tdwn/$tup</td><td>$icdwn/$icup</td><td>$total_traf</td><td>$diff_traf</td></tr>\n";
	    } else {
		print OF "<tr><td>$iid</td><td>$nick</td><td>$tdwn/$tup</td><td>$icdwn/$icup</td><td>$total_traf</td><td>$diff_traf</td></tr>\n";
	    }
	}    
	print OF $default_row;
	print OF "</table>\n";
	print OF "$count zaznamu\n";
    }
}

sub print_user_stats {
    my ($sum_hour,$sum_total) = @_;
    print " sum_stats";
    print OF "<h2>Soucty na vsech interfacech</h2>\n";
    print OF "<h3>&nbsp;</h3>\n";
    print OF "<table title='datas' style='text-align:center'>\n";
    print OF "<tr><th style='width:5em'>ID</th><th style='width:5em'>nick</th><th>total [B]</th><th>obdobi [B]</tr>\n";

    my @pole =();
    my $count=0;
    while (my ($id,$data) = each (%{$sum_total})) {
	push @pole, $id;
	$count++;
    }
    @pole = sort {$a <=> $b} @pole;
    foreach (@pole) {
        my $iid = $_;
	my $diff_traf = $sum_hour->{$iid};
	my $total_traf = $sum_total->{$iid};
	$total_traf=jednotky($total_traf);
	$diff_traf=jednotky($diff_traf);
	my $nick="neznamy";
	if (exists($nicks->{"$iid"})) {
	    $nick=$nicks->{"$iid"};
	}
	print OF "<tr><td>$iid</td><td>$nick</td><td>$total_traf</td><td>$diff_traf</td></tr>\n";
    }	
    print OF "</table>";
    print OF "$count zaznamu\n";
}

sub print_bans {
    print " bans";
    print OF "<h2>Bany a banany</h2>\n";
    print OF "<h3>Fixni nastaveni rychlosti</h3>\n";
    if (open TF, "$DATADIR/class-ban") {
	print OF "<table title='bans'  style='text-align:center'>\n";
	print OF "<tr><th style='width:5em'>ID</th><th>zarizeni</th><th>rate</th><th>ceil</th><th>poznamka</th></tr>\n";
	while (<TF>) { 
	    my ($tid, $tface, $trate, $tceil) = split;
	    my ($tmpt, $tcomment) = split ("#",$_);
	    if ($tmpt) {
		print OF "<tr><td>$tid</td><td>$tface</td><td>$trate</td><td>$tceil</td><td>$tcomment</td></tr>\n";
	    }
	}
	close TF;
	print OF "</table>";
    } else {
	print OF "<p><i>neni aktivovano</i></p>\n";
    }
    print OF "<h3>Bany spravcu pres IS</h3>\n";
    `cat $DATADIR/autoban/* >$DATADIR/autoban.txt`;
    if (open TF, "$DATADIR/autoban.txt") {
	print OF "<table title='bans'  style='text-align:center'>\n";
	print OF "<tr><th style='width:5em'>ID</th><th>nick</th><th>zarizeni</th><th>rate</th><th>ceil</th><th>poznamka</th></tr>\n";
	while (<TF>) { 
	    my ($tid, $tface, $trate, $tceil) = split;
	    my ($tmpt, $tcomment) = split ("#",$_);
	    my $nick="neznamy";
	    if (exists($nicks->{"$tid"})) {
		$nick=$nicks->{"$tid"};
	    }
	    if ($tmpt) {
		print OF "<tr><td>$tid</td><td>$nick</td><td>$tface</td><td>$trate</td><td>$tceil</td><td>IS ban</td></tr>\n";
	    }
	}
	close TF;
	print OF "</table>";
    } else {
	print OF "<p><i>zadny aktivni</i></p>\n";
    }

    print OF "<h3>Aktivni omezeni</h3>\n";
    `cat $DATADIR/penalty* >$DATADIR/pen.txt`;
    if (open TF, "$DATADIR/pen.txt") {
	print OF "<table title='bans2'  style='text-align:center'>\n";
	print OF "<tr><th>ID</th><th>nick</th><th>[%]</th><th>poznamka</th></tr>\n";
	while (<TF>) { 
	    my $line = $_;
	    $line =~ s/#.*// ;chomp($line);
	    if (length($line) > 0) {
		my ($tid, $tperc, @trest) = split;
		my $tcom = join (" ",@trest);
		my $nick="neznamy";
		if (exists($nicks->{"$tid"})) {
		    $nick=$nicks->{"$tid"};
		}
		print OF "<tr><td>$tid</td><td>$nick</td><td>$tperc</td><td>$tcom</td></tr>\n";
	    }
	}
	close TF;
	print OF "</table>";
    } else {
	print OF "<p><i>zadny aktivni</i></p>\n";
    }

    close TF;
    print OF "<h3>Zabanovane IP:</h3>\n";
    open TF, "$QOSDIR/ban_ip";
    while (<TF>) {
	print OF "$_ <br>\n";
    }
    close TF;
}


sub print_system_table {
    my ($sysclass, $face, @p2) = @_;
    
    print OF "<h3>$face</h3>\n";
    print OF "<table title='system' style='text-align:center'>\n";
    print OF "<tr><th>id</th><th>rate</th><th>ceil</th><th>crate</th><th>send</th><th>drop</th><th>popis</th></tr>\n";
    foreach (@p2) {
        my $popis="";
        my $id = $_;
        my $tmp = $sysclass->{$face}->{$id};
        #print "$face:$id\n";
        my $color="";
        if ($id eq "5") {
            $color="bgcolor='#33CCFF'";
            $popis ="system:ssh";
        } elsif ($id eq "1") {
            $popis="total"
        } elsif ($id eq "2") {
            $popis="system"
        } elsif ($id eq "3") {
            $popis="small packet";
        } elsif ($id eq "4") {
            $popis="user class";
        } elsif ($id eq "6") {
	    $color="bgcolor='#66CC00'";
            $popis = "system:icmp";
    	} elsif ($id eq "7") {
	    $color="bgcolor='#CCCC00'";
    	    $popis = "system:dns";
        } elsif ($id eq "8") {
            $color="bgcolor='#FFCCFF'";
            $popis = "system:mgmt";
        } elsif ($id eq "9") {
	    $color="bgcolor='yellow'";
	    $popis = "ack";
        } elsif ($id eq "666") {
            $color="bgcolor='#FF9999'";
	    $popis="ban class";
        }
        my $send = jednotky($tmp->{"send"});
	print OF "<tr><td $color>$id</td><td $color>$tmp->{crate}</td><td $color>$tmp->{cceil}</td><td $color>$tmp->{rrate}</td><td $color>$send</td><td $color>$tmp->{drop}</td><td $color>$popis</td></tr>\n";
    }
    print OF "</table>\n";
}

sub print_system_classes {
    my ($conf,$sysclass) = @_;
    print " system";
    #temporary sort arrays
    my %h1; my @p1 =(); my @p2 =();
    while (my ($face,$fdata) = each (%{$sysclass})) {
	while (my ($iid,$data) = each (%{$fdata})) {
    	    $h1{"$iid"}=$iid;
	}
    }
    while (my($face)=each(%{$conf})) {push @p1, $face;}
    while (my($iid)=each(%h1)) {push @p2, $iid;}
    @p1 = sort @p1;
    @p2 = sort {$a <=> $b} @p2 ;

    foreach (@p1) {
        my $face = $_;
        if ($face =~ /imq/ ) {
            next;
        }
        print_system_table ($sysclass,$face,@p2);
	#print "D:$face $interfaces{$face} \n";
        if ($conf->{$face}->{queues} ne $face ) {
            print OF "</td><td>\n";
    	    print_system_table ($sysclass,$conf->{$face}->{queues},@p2);
	}
	print OF "</td></tr><tr><td>\n";
    }
}

# ==================================================================

sub genHtml {
    my ($conf_data,$pnicks,$rc,$if_total, $sum_hour, $sum_total, $sysclass, $ctime, $filen) = @_;
    if (not (defined ($filen))) { $filen = $HTMLOUTFILE; };
    $nicks=$pnicks;
    open OF, ">$filen.tmp";
    print "   Printing:\n      ";
    #static head
    open TF, "$QOSDIR/scripts/userap_files/html_templates/traffic_head";
    while (<TF>) { print OF "$_"; } close TF;
    my $now = localtime();
    #my $ctime = (stat("/var/run/userapd"))[9];
    my $first = "";
    if (!$ctime) {
	$first = "neznamo";
    } else {
        $first = localtime($ctime);
    }
    print OF "<i>Naposledy aktualizovano: $now <br>\n";
    print OF "Statistiky za obdobi od: $first </i><br><br>\n";
	
    print OF "<h1>Informace pro cleny</h1>\n";
    print OF "<table width='780'><tr>\n";
    print OF "<td valign='top' bgcolor='#efefef'> \n";
    print_iface_stats($conf_data,$rc,$if_total,$sum_total,$sum_hour);
    #print_user_stats($sum_hour,$sum_total);
    print OF "</td><td valign='top' bgcolor='#efefef'>\n";
    print_bans();
    print OF "</td></tr></table>\n";
		
    print OF "<br><br>\n<h1>Informace pro zasvecene</h1>\n";
    print OF "<table width='780'><tr>\n";
    print OF "<td colspan=2 valign='top' bgcolor='white'> \n";
		
    print_general_data();
    print_config_data($conf_data);
    print OF "</td></tr><tr><td colspan=2>\n";
    print OF "<h2>Systemove tridy</h2></td></tr><tr><td>\n";

    print_system_classes($conf_data,$sysclass);
    print OF "</td></tr></table>\n";

    open TF, "$QOSDIR/scripts/userap_files/html_templates/traffic_tail";
    while (<TF>) { print OF "$_" ;} close TF;
    system ("mv $filen.tmp $filen");
    `cp $COUNTERSTATFILE /var/www/tc_dump.xml`;
    print "\n";
}		
		
1;