#!/usr/bin/perl
#
#  Copyright 1997 Yukinori Koike  Ver 1.9C
#
#  Usage: CGI LogWriter.pl?log=log_filename&prev=reffer&diff=time_diff
#         SSI LogWriter.pl log_filename time_diff
#
#
# Check number of parameter
#
if ( $ENV{'QUERY_STRING'} )
{
	#
	# For CGI
	#
	print "Content-type: image/gif\n\n";
	$str = $ENV{'QUERY_STRING'};
	@part = split('&',$str,3);
	foreach $pair (@part)
	{
        	($variable,$value) = split('=',$pair,2);
        	if ( $variable eq "log" || $variable eq "LOG" )
		{
			$LOGFILE = $value;
		}
        	elsif ( $variable eq "diff" || $variable eq "DIFF" )
		{
			if ( $value ne "0" )
			{	
				$TIME_DIFF = $value;
			}
		}
        	elsif ( $variable eq "prev" || $variable eq "PREV" )
		{
			$PREV = $value;
		}
	}
}
else
{
	#
	# For SSI
	#
	print "Content-type: text/html\n\n";
	$LOGFILE = @ARGV[0];
	$TIME_DIFF = @ARGV[1];
}

# Time difference
if ( $TIME_DIFF )
{
	$ENV{'TZ'} = "JST$TIME_DIFF";
}

# DATE
@bdate = localtime;
$rec = sprintf("{+}{BDATE:20%02d%02d%02d%02d%02d%02d}",substr(@bdate[5],1),@bdate[4]+1,@bdate[3],@bdate[2],@bdate[1],@bdate[0]);
# IP
if ($ENV{'REMOTE_ADDR'})
{
        $ip = sprintf("{IP:%s}",$ENV{'REMOTE_ADDR'});
        $rec = sprintf("%s%s",$rec,$ip);
}
# HOST
if ($ENV{'REMOTE_HOST'})
{
        $host = sprintf("{HOST:%s}",$ENV{'REMOTE_HOST'});
        $rec = sprintf("%s%s",$rec,$host);
}
else
{
	if ($ENV{'REMOTE_ADDR'})
	{
        	$host = gethostbyaddr(pack("C4",split(/\./,$ENV{'REMOTE_ADDR'})),2);
		if ( $host )
		{
        		$rec = sprintf("%s{HOST:%s}",$rec,$host);
		}
       		#$rec = sprintf("%s{HOST:%s}",$rec,$ENV{'REMOTE_ADDR'});
	}
}
# BROWSER
if ($ENV{'HTTP_USER_AGENT'})
{
        $browser = sprintf("{BROWSER:%s}",$ENV{'HTTP_USER_AGENT'});
        $rec = sprintf("%s%s",$rec,$browser);
}
# PREVIOUS ADDR
if ( $PREV )
{
        $prev_url = sprintf("{URL:%s}",$PREV);
        $rec = sprintf("%s%s",$rec,$prev_url);
}
elsif ($ENV{'HTTP_REFERER'})
{
        $prev_url = sprintf("{URL:%s}",$ENV{'HTTP_REFERER'});
        $rec = sprintf("%s%s",$rec,$prev_url);
}

# Write to Access Log File
open(FILE ,"+< $LOGFILE");
eval { flock(FILE,2); };
seek(FILE,0,2);
$rec = sprintf("%s\n",$rec);
print FILE $rec;
seek(FILE,0,0);
$cnt = 0;
while (<FILE>)
{
	if ( 0 == index($_,'{+}') )
	{
		$cnt++;
	}
}

# Create Access Count File
$CNTFILE = $LOGFILE;
$CNTFILE =~ s/wit$/cnt/;
if ( $CNTFILE =~ /$LOGFILE/ )
{
	eval { flock(FILE,8); };
	close(LFILE);
	exit;
}
open(CFILE ,"+< $CNTFILE");
eval { flock(CFILE,2); };
truncate(CFILE,0);
seek(CFILE,0,0);
print CFILE $cnt;
eval { flock(CFILE,8); };
close(CFILE);

# Close Access Log File
eval { flock(FILE,8); };
close(FILE);
