#!/usr/bin/perl
# print "Content-type: text/html\n\n";

$filename = $ENV{"FILE"};
# print "FILE defined as $filename\n";

$data = sprintf("%s %s", $ENV{"USER"}, $ENV{"REMOTE_HOST"});

&lock_file ($filename, 5)
	|| &send_error ("Couldn't lock file '$filename'.\n", $filename);

unless (open (FILE, "$filename")) {
    &unlock_and_die ($filename,
                     "Couldn't open file '$filename' for reading.\n",
		     $filename);
    }

$firstline = <FILE>;
unless ($firstline eq "sbloch counter file\n") {
   &unlock_and_die ($filename, "attempt to count hits using file '$filename' starting with '$firstline'.\n",
     $data);
   }

$count = <FILE>;
close (FILE);

unless ( open (FILE, ">$filename")) {
	&unlock_and_die ($filename, "Couldn't open file '$filename' for writing.\n",$count+1);
	}

print FILE "sbloch counter file\n";
print FILE $count+1;
close FILE;
&unlock_file ($filename);

print "$count";

sub unlock_and_die {
	local ($filename, $msg, $info) = @_;
	&unlock_file ($filename);
	&send_error ($msg, $info);
	}

sub lock_file {
	local ($file_name, $numtries) = @_;
	my ($i,$lock_file_name);

	$lock_file_name = &build_name ($file_name);
	# print "Locking '$lock_file_name'\n";
	# try several times, waiting a second in between
	for ($i = 1; $i <= $numtries; ++$i) {
		# true if the lock file was created
		if ( symlink ($file_name, $lock_file_name)) {
			# print "Successfully linked $file_name to $lock_file_name\n";
			return 1;	# yay!
			}
		sleep 1;
		}
	# print "Failed repeatedly to link $file_name to $lock_file_name\n";
	return 0;	# we failed
	}

sub unlock_file {
	local ($file_name) = @_;
	my $lock_file_name;
	$lock_file_name = &build_name($file_name);
	# print "Unlocking '$lock_file_name'\n";
	unlink ($lock_file_name);
	}

sub build_name {
	local ($file_name) = @_;
	my $lock_file_name;
	$lock_file_name = $file_name . ".lck";
	$lock_file_name =~ s/\.\.\///g;
	$lock_file_name =~ s/\//-/g;
	$lock_file_name = "/tmp/" . $lock_file_name;
	return $lock_file_name;
	}
	

sub send_error {
    local ($error_msg, $text) = @_;

    open(MAIL, "|/usr/sbin/sendmail -t") 
        || die "Couldn't mail: $!";
    print MAIL <<"EOM";
To: sbloch\@adelphi.edu
Subject: $0: $error_msg
\n\n$0 was unable to complete because of the following error:
\n$error_msg
\n\nThe following needs to be processed by hand:
\n\n$text
\n.\n
EOM
    close (MAIL);

#     print  <<"ERROR_RESPONSE_PAGE";
# <title>Thanks for your response</title>
# <H1>Thanks for your response</H1>
# The system is a little confused right now, so we weren't
# able to process the data you submitted.  However, it has
# been recorded and mailed to the owner of the page, who 
# will process it by hand later.
# ERROR_RESPONSE_PAGE

    die "$error_msg";
}


