#!/usr/local/bin/perl
#  
#########################################################################
#CGIカウンター簡易版  TcounT Lite Ver.2.XX  (c) Takahiro Nishida 98/2/3 #
#          (質問等は下記ページの専用掲示板で受け付けています)           #
#                     http://www2s.biglobe.ne.jp/~tnishida/             #
#########################################################################
#
###(変数設定部)詳細は上記ページをご覧下さい。######################
$basedir=".";
###(変数設定部)ここまで#########################################

$lockfile="$basedir/lockdir/tc.lock";

$| = 1;

require 'gifcat.pl';

&main;

sub main{
	&check_input;
	&file_lock;
	&show_counter;
	unlink($lockfile);
}

sub check_input{
	$buffer = $ENV{'QUERY_STRING'};
	@prm = split("&", $buffer);
	unless($prm[0]=~/^\w+$/){ &show_error("",3); }
	unless($prm[1]==0){ $prm[1]=1; }
	unless($prm[2]=~/^\d+$/){ $prm[2]=5; }
	unless($prm[3]=~/^\w+$/){ $prm[3]="img"; } 
}

sub show_counter{
	$cntfile="$basedir/data/$prm[0].txt";
	unless(-f $cntfile){ &show_error($cntfile, 2); }

	open(NUM,"$cntfile") || die &show_error($cntfile, 2);
	$cnt=<NUM>;
	close(NUM);

	if($prm[1]){
		$cnt = &increase_count($prm[0], $cnt);
	}
	
	$cnt =~ s/\n//ig;
	&show_number_image($cnt, $prm[2], $prm[3]);
}

sub increase_count{
	local($file, $cntnow) = @_;
	$cntfile="$basedir/data/$file.txt";
	
	$cntnow++;
	open(NUM,">$cntfile") || die &show_error($cntfile,1);
	print NUM $cntnow;
	close(NUM);

	return $cntnow;
}

sub show_number_image{
	local($cnt, $keta, $type) = @_;
	
	unless(-f "$basedir/$type/1.gif"){
		&show_error("$basedir/$type/1.gif",2);
	}

	@nos=split("",$cnt);
	while(@nos<$keta){ unshift(@nos, "0"); }
	for(0..$#nos){ $nos[$_]="$basedir/$type/$nos[$_].gif"; }

	print "Content-type: image/gif\n\n";
	binmode(STDOUT);
	print &gifcat'gifcat(@nos);
}

sub file_lock{
	if((-M "$lockfile")>0.0004){ unlink($lockfile); }
	$try=5;
	while(!(symlink("$$",$lockfile))){
		if(--$try<=0){ &show_error("",0); }
	sleep(1);
	}   
}

##############################################
# symlink が使えないサーバー用のファイルロック
##############################################
#sub file_lock{
#	if((-M "$lockfile")>0.0004){ unlink($lockfile); }
#	$try=5;
#	while(-f $lockfile){
#		if(--$try<=0){ &show_error("",0); }
#		sleep(1);
#	}
#	open(FILE,">$lockfile") || die &show_error("",0);
#	close(FILE);
#}
##############################################

sub show_error{
	unlink($lockfile);
	($fname, $msgno)=@_;
	
	@msg=('ロック中です'
	     ,'に書き込めません'
	     ,'がありません'
	     ,'パラメータが不正です'
	     );

	print "Content-type: text/plain\n\n";
	print "<< Error Message from TcounT Lite >>\n";
	print "$fname$msg[$msgno]";

	exit;
}
