#!/usr/local/bin/perl

use Image::Magick;
use CGI;

$| = 1;

my $ref = $ENV{HTTP_REFERER};

if($ref=~m:$ENV{HTTP_HOST}:) {
    $inc = 1;
} else {
    print "x-warning: Counters for other domains are not supported\n";
}

my $q = new CGI;

my $cname = $q->param('c') || "tmp";

$cname=~s:[^a-zA-Z0-9]::gs;
print "x-real-counter: $cname\n";
open FH,"< /home/jason/websites/counters/$cname";
my $val = int(<FH>) || 0;
close FH;
$inc = 0 if(defined $q->param('n'));

my $from = $ENV{HTTP_X_FORWARDED_FOR} || $ENV{REMOTE_ADDR};
#$inc = 0 if($from=~m:^(82\.68\.159\.2\d\d)|(10\.0\.0.\d{1,3})|(194\.154\.182\.\d{1,3})|(10\.1\.\d{1,3}\.\d{1,3})$:);

$inc = 0 if(defined $q->param('noinc'));

if($inc) {
    my $c = 0;
    
    while(($c < 5) && (-d "/home/jason/counters/.$cname")) {
	$c++;
	print "x-sleep-$c: waiting\n";
	sleep(1);
    }
    
    mkdir "/home/jason/websites/counters/.$cname";
    $val++;
    open FH,"> /home/jason/websites/counters/$cname";
    print FH "$val\n";
    close FH;
    print "x-counter-is-now: $val\n";
    rmdir "/home/jason/websites/counters/.$cname";
    print "Expires: 0\n";
}

my $i = new Image::Magick;

my $c = new Image::Magick;
my $sz = $q->param('z') || 0;

my @srcs = ("basic", "large", "clean", "bold", "computer", "fancy", "neat", "script", "weedy", "fat", "sharp", "classic", "script2", "scriptbold", "scifi", "playtime", "hollow", "comic", "copper", "curls", "huge");

$src = $srcs[$sz] || "basic";
$c->Read("/home/jason/websites/cgi-bin/counters/$src.gif");
print "x-style: $sz\n";

my $ih = $c->Get('height');
my $sw = $c->Get('width') / 10;

my $w = ($q->param('w') || 8);
my $iw = $w * ($sw);

$val = sprintf("%-.${w}d", $val);
print "x-counter-padded: $val\n";

print "Content-type: image/gif\n\n";

$i->Set(size=>"${iw}x${ih}");
$i->Read("xc:black");
$i->Set(magick=>"gif");

my $x = 0;
while($val=~m:(\d):g) {
    my $a = $1;
    my $xp = int($a) * $sw;
    print "$x $a $xp\n" if($ENV{TERM});
    for($xx = 0; $xx < $sw; $xx++) {
	for($yy = 0; $yy < $ih; $yy++) {
	    $i->Set("pixel[" . int($xx + $x) . ",$yy]" =>
		    $c->Get("pixel[" . int($xp + $xx) . ",$yy]"));
	}
    }
    $x += $sw;
}

if(!defined $ENV{TERM}) {
    binmode STDOUT;
    my @b = $i->ImageToBlob();
    print $b[0];
}
