#!/usr/bin/perl
# (c) 2006 by cato@xenim.de
# licenced under Terms of GPLv2

use RRDs;
my $USER = "";
my $PASS = "";

use Digest::MD5 qw(md5_hex);
use DBI;
use XML::Simple;

my @dsn = ("DBI:mysql:database=db;" .
           "host=localhost", $USER, $PASS);

# Datenbank andocken
my $dbh = DBI->connect(@dsn,
     { PrintError => 0,
       AutoCommit => 1,
     }
          ) or die $DBI::errstr;
my $aref = $dbh->selectall_arrayref("SELECT listen_url,listeners FROM server_details") or die $dbh->errstr();
$png = "/var/www/stream/history.png";
$storedir = "/usr/local/var/cache/rrd/";

for my $row (@$aref) {	
	my($url, $listeners) = @$row;
	#print $url, $listeners;
	
	$file = $storedir.md5_hex($url).".rrd";
	if(!-e $file) {
		RRDs::create ($file,
		"--step",300,
		"DS:listeners:GAUGE:600:0:U",
		"RRA:AVERAGE:0.5:1:180",
		"RRA:AVERAGE:0.5:12:720",
		);
		if (my $ERROR = RRDs::error) {
			print "ERROR: $ERROR\n";
		};
		my $ref = XMLin('/usr/local/var/cache/rrd/streams.xml', ForceArray => [ stream ]);
		push(@{ $ref->{stream} },{md5=>md5_hex($url), url=>$url});
		XMLout($ref, OutputFile => '/usr/local/var/cache/rrd/streams.xml', NoAttr => 1, RootName => streams);

	}
	RRDs::update $file, "N:$listeners";
	if (my $ERROR = RRDs::error) {
		print "ERROR: $ERROR\n";
	};
}

@data = ($png);
push(@data,"--start=end-5h");
push(@data,"--end=now");
#push(@data,"--vertical-label=$lable");
push(@data,"--width=600");
push(@data,"--height=100");
push(@data,"--lazy");
#push(@data,"--slope-mode");
push(@data,"--imgformat=PNG");
#push(@data,"--watermark=stream.xenim.de");
push(@data,"--title=Verlauf der Hoererzahlen");
opendir DH, $storedir;
$i = 0;
my $ref2 = XMLin($storedir.'streams.xml', ForceArray => [ stream ], KeyAttr => "md5");
while ($file = readdir DH) {
	$ident = substr($file,0,-4);
	if ( $file =~ /^\./ or $file !~ /rrd$/ ) { next };
	#print "file: ".$file." : ".$ident."\n";
	push(@data,"DEF:$i=/usr/local/var/cache/rrd/$file:listeners:AVERAGE");
	if ($i != 0) { $do = "STACK"; }
		else { $do = "AREA"; }
	$ref2->{stream}->{$ident}->{url} =~ s/:/\\:/g;
	$do = $do.":$i#".substr($ident,0,6).":".$ref2->{stream}->{$ident}->{url}.":";
	push(@data, $do);
	$i++;
}
closedir DH;
#print @data;
RRDs::graph (@data);
if (my $ERROR = RRDs::error) {
	print "ERROR: $ERROR\n";
};

