#!/usr/bin/perl
# Verbrochen von: Sven Weise <sven.weise@unit0.net>
#
# Generates a picture of the ranking on top1000.org for the last 31 Days
#
# Free of use/modification
#
# Fileformat; each day one line; only the last 31 entrys are counting:
# Unix-Timestamp Rank-From-Top1000 Pathhost
# ---
# 1237352400 218 news.unit0.net
# 1237438801 217 news.unit0.net
# 1237525200 217 news.unit0.net
# ---

# Generated with something like
# ---
# perl -e 'print time." ";' >> /news/log/top1000_history_daily.log
# wget -q http://www.top1000.org/top1000.current.txt -O - | grep 'unit0.net' | awk '{print $1 " " $3}' >> /news/log/top1000_history_daily.log
# ---



use strict;
use GD;

my $file='/news/log/top1000_history_daily.log';
my (@data,@slice);
open(F, "<$file");
while (chomp(my $line=<F>)) {
	my (@tmp)=split(/ /,$line);
	push @data, $tmp[1];
}
close(F);

if (scalar(@data) >= 31) {
	my $count=@data;
	my $idx=$count-31;
	@slice=@data[$idx..$count];
}
if (@slice) { @data=@slice }

# Bildobjekt; (width,height)
my $bild = new GD::Image(651,651);

# Erzeuge Farben
# Die erste Farbe die definiert wird wird automatisch die Hintergrundfarbe.
my $weiss = $bild->colorAllocate(255,255,255);
my $schwarz = $bild->colorAllocate(0,0,0);
my $blau = $bild->colorAllocate(0,0,255);
my $rot = $bild->colorAllocate(255,0,0);
my $gelb=$bild->colorAllocate(233,244,123);

# Transparenter Hintergrund
$bild->transparent($weiss);

# Interlaced
$bild->interlaced('true');

my $next=40;
for my $dat (@data) {
	$bild->arc($next,$dat,5,5,0,360,$blau);
	$bild->fill($next,$dat,$blau);
	my $txtidx=$next-7;
	$bild->string(gdSmallFont,$txtidx,$dat,$dat,$schwarz);
	$next=$next+20;
}

#Draw grid
for (0 ... 60) {
	my $idx=$_*10;
	# - = x
	$bild->line(0,$idx,650,$idx,$rot);
}
for (0 ... 66) {
	my $idx=$_*10;
	# Erst am dem 30. pixel und dann nur alle ungeraden (20pixel) einen Strich
	if (($_ >= 3) && ($_ & 1)) {
		# | = y
		$bild->line($idx,0,$idx,620,$rot);
	}
}

# Labels
for (1 ... 60) {
	my $label=$_*10;
	my $idx=$label-10;
	$bild->string(gdSmallFont,5,$idx,$label,$blau);
}
for (1 ... 31) {
	#my $idx=(($_*10)*2)+15;
	my $idx=655-(($_*10)*2);
	my $label=sprintf("%02d",$_);
	$bild->string(gdSmallFont,$idx,605,$label,$blau);
}

# Legend
$bild->string(gdSmallFont,300,620,'Days ago',$schwarz);


# Das ganze in Datei als PNG ausgeben
open(F, "> /news/www/bild.png");
print F $bild->png;
close(F);

