#!/usr/bin/perl 
# $Id: $

use strict;
use vars qw (@data);

my $filepath="/usr/local/netcore/data/46meter/cnt/";
my $prefix="/46meter";

my $u = 0;

my @query_pair = split('&', $ENV{'QUERY_STRING'});
my $pair;
foreach $pair (@query_pair){
    my ($name, $value) = split('=', $pair);
    $value =~ tr/+/ /;
    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
    if ($name eq 's') {
        $u = $value;
        last;
    }
}
my $display=1;
$display = 0 if (length $u >= 64);
$display = 0 if ($u =~ /[^\w\-_\.]/);

print "Content-type: text/html\n";
print "\n";

exit 0 if (!$display);

my $nodata = read_data("$filepath/$u.cnt");
	
html_head();

if (!$nodata) {
    create_html_graph();
}

if($ENV{'HTTPS'} =~ /on/){
html_ssl_tail();
} else {
html_tail();
}
exit 0;

#
sub read_data {
    my ($filename) = @_;
    my $i;

    return 1 if(! -f $filename);
    open(FD, "< $filename") || return 1;
    for($i=0; $i<30; $i++){
        $data[$i] = "";
    }
    $i = 0;
    while (<FD>) {
        chop;
        my ($ipv4, $ipv6) = split(/ /);
        if ($ipv4 == 0 && $ipv6 == 0) {
            $data[$i] = "";
        } else {
            $data[$i] = $ipv6;	
        }
        $i++;
    }
    close(FD);
    return 0;
}

#
sub create_html_graph {
    my ($i);
    my ($v6ratio);

    my $nodata = 1;
    for ($i=29;$i>=0;$i--) {
        print "<td>";
        if ($data[$i] eq "") {
            printf ("<img alt=\"no data\" src=\"%s/images/non.png\">", $prefix) if (!$nodata);
        } else {
            $nodata = 0;
            $v6ratio = (int (($data[$i]+5)/10))*10;
            printf ("<img alt=\"%d\%\" src=\"%s/images/%02d.png\">", $data[$i], $prefix, $v6ratio);
        }
        print "</td>";
    }
}

#
sub html_head {
    print << "---";
<html>
<head>
<style type="text/css">
<!--
#all       {display:block;width:160px;height:110px;}

body {
  background-repeat: no-repeat;
  background-image: url(/46meter/images/ipv4ipv6meter.gif);
  background-color: transparent;
}

#meter {
  top: 24px;
  left: 5px;
  width: 150px;
  height: 61px;
  position: absolute;
}

td {
  width: 5px;
}

-->
</style>
</head>
<body>
<table id="meter" cellspacing=0 cellpadding=0>
<tr>
---
}

#
sub html_tail {
    print << "---";
</tr>
</table>
<a id="all" href="http://inetcore.com/project/46meter/" target="_blank"> 
</a>
</body>
</html>
---
}

sub html_ssl_tail {
    print << "---";
</tr>
</table>
<a id="all" href="https://inetcore.com/project/46meter/" target="_blank"> 
</a>
</body>
</html>
---
}
