#!/opt/local/bin/perl

$image_file = "../gfx/tracking.jpg";
#$image_file = "/dev/null";
$log_file = "cRyPtIcFiLeNaMe";
$show_title = "Stats for $ENV{'REMOTE_ADDR'}";
$omit_title = "Omitting $ENV{'REMOTE_ADDR'}";
$info = "Recorded by <tt>track</tt>, version 0.01, by Kevin Peterson";
if($ENV{'QUERY_STRING'} eq 'show') {
    &record();
    &show_log();
} elsif ($ENV{'QUERY_STRING'} eq 'sesame') {
    &omit_log();
} else {
    &record();
    print "Content-type: image/jpeg\n\n";
    open(IMAGE, $image_file) or $open_error = "an error occured: $!";
    while ( read IMAGE, $buf, 16384) {
	print $buf;
    }
}
exit (0);

sub show_log() {
    print "Content-type: text/html\n\n";
    print "<HTML>\n";
    print "<HEAD><TITLE>$show_title</TITLE></HEAD>\n";
    print "<BODY>\n<H1>$show_title</H1>\n<H2>$info</H2>\n<TABLE>\n";
    if(open(LOG, $log_file)) {
	while($line = <LOG>) {
	    if(index($line, $ENV{'REMOTE_ADDR'}) > 0) {
		print $line;
	    }
	}
    } else {
	print "<TR><TD>an error occured</TD></TR>\n";
    }
    print "\n</TABLE>\n</BODY>\n</HTML>";
}

sub omit_log() {
    print "Content-type: text/html\n\n";
    print "<HTML>\n";
    print "<HEAD><TITLE>$omit_title</TITLE></HEAD>\n";
    print "<BODY>\n<H1>$omit_title</H1>\n<H2>$info</H2>\n<TABLE>\n";
    if(open(LOG, $log_file)) {
	while($line = <LOG>) {
	    unless(index($line, $ENV{'REMOTE_ADDR'}) > 0) {
		print $line;
	    }
	}
    } else {
	print "<TR><TD>an error occured</TD></TR>\n";
    }
    print "\n</TABLE>\n</BODY>\n</HTML>";
}

sub record() {
    ($sec, $min, $hour, $mday, $mon, $year) = localtime(time);
    if 0 {
    #if(open(LOG, ">>$log_file")) {
        printf LOG "<TR><TD>%04d%02d%02d</TD>", $year + 1900, $mon + 1, $mday;
	printf LOG "<TD>%02d:%02d:%02d</TD>", $hour, $min, $sec;
	print LOG "<TD>$ENV{'REMOTE_ADDR'}</TD>";
	print LOG "<TD>$ENV{'REMOTE_HOST'}</TD>";
	print LOG "<TD>$ENV{'QUERY_STRING'}</TD>";
	print LOG "<TD>$ENV{'HTTP_USER_AGENT'}</TD>";
	print LOG "</TR>\n";
        close LOG;
    }
}
