#!/usr/athena/bin/perl

use strict;
use Fcntl;

my $referer = $ENV{'HTTP_REFERER'} || '';
if (substr($referer, 0, 26) eq "http://www.celebboard.com/")  {
#  print "Content-Type: image/jpeg\nContent-Length: 2\n\nX\n";
#  exit 0;
}
if (substr($referer,0,24) eq "http://www.acidtrip.com/") {
#  print "Content-Type: image/jpeg\nContent-Length: 2\n\nX\n";
#  exit 0;
}
if (substr($referer,0,36) eq "http://www.tnt-hosting.com/srh0517a/") {
#  print "Content-Type: image/jpeg\nContent-Length: 2\n\nX\n";
#  exit 0;
}

my $maxcache = 0;

sub png {
  my($num) = @_;
  print("Content-type: image/png\n\n");
  if ($num !~ /^\d+$/) {
    exit;
  }
  require "GD.pm";
  my $digits = 1 + int(log($num) / log(10));
  my $im = new GD::Image($digits * 8 + 4, 16 + 4);
  my $white = $im->colorAllocate(255,255,255);
  my $black = $im->colorAllocate(0,0,0);
  $im->fill(1,1,$black);
  $im->string(GD::Font->MediumBold,4,3,$num,$white);
  print $im->png();
}

my $key = $ENV{'PATH_INFO'};

if (($key eq "") || ($key eq "/")) {
  # If no key is given, default to directions page.
  print "Location: http://stuff.mit.edu/doc/counter-howto.html\n\n";
} else {  
  open(LOCK, ">>/var/www/data/counter.lock");
  my $lock = pack('s s l l s', &F_WRLCK, 0, 0, 0, 0);
  fcntl(LOCK, &F_SETLKW, $lock);
  #flock(LOCK, $LOCK_EX);
  my %counterdb;
  dbmopen(%counterdb, "/var/www/data/counterdb", 0777);
  $counterdb{$key}++;
  my $val = $counterdb{$key};
  dbmclose(%counterdb);
  $lock = pack('s s l l s', &F_UNLCK, 0, 0, 0, 0);
  fcntl(LOCK, &F_SETLK, $lock);
  png($val);
}
