#!/usr/local/bin/perl
# absolute data path
$data_dir = "/user/yoonforh/public_html/bin/counter/data/"; 
# default count data filename
$count_file = "count.txt";

@referers = ("moon.daewoo.co.kr","www.daewoo.net","165.133.1.5");

&parse_query;
&check_referer;
&get_num;

sub parse_query {
	# Get the input
	($name, $value) = split(/=/, $ENV{'QUERY_STRING'});
	$value =~ tr/+/ /;
	$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
	$FORM{$name} = $value;
}

sub check_referer {
   if (@referers && $ENV{'HTTP_REFERER'}) {
      foreach $referer (@referers) {
         if ($ENV{'HTTP_REFERER'} =~ /$referer/) {
            $ref = 1;
            last;
         }
      }
   }
   else {
      $ref = 1;
   }

   if ($ref != 1) {
      print "-1\n\n";
      exit;
   }
}

# use Fcntl ':flock'; # import LOCK_* constants
# adding flock 1998/10/28 - yoonforh

sub LOCK_EX { 2 }
sub LOCK_UN { 8 }

sub get_num {

	if ($FORM{'data'} eq '') {
		$count_file="count.txt";
	}
	else {
		$count_file=$FORM{'data'};
	}

	use Fcntl;
	sysopen(FH, "$data_dir/$count_file", O_RDWR|O_CREAT, 0644) or die "can't open numfile: $!";
	flock(FH, 2) or die "can't flock numfile: $!";
	$count =  || 0;
	seek(FH, 0, 0) or die "can't rewind numfile: $!";
	truncate(FH, 0) or die "can't truncate numfile: $!";
	(print FH $count+1, "\n") or die "can't write numfile: $!";
	# DO NOT UNLOCK THIS UNTIL YOU CLOSE
	close FH or die "can't close numfile: $!";

	print "Content-type: text/plain\n\n";
   print "$count";
}