$LOCK_OK = 0;
$LOCK_NOT_OK = 1;

$SLEEP = 5;

chop($hostname = `/bin/hostname`);

#locks either the entire system or an individual file
#NOTE: this needs to have an abort/retry option
#
sub lock {
	local($tolock, $timeout) = @_;
	local($TMPFILE,$LOCKFILE,$tries);

	$LOCKFILE = $tolock;
#	print "(Attempting to lock problem/request #$request.";
	$TMPFILE = "$LOCKFILE.$hostname.$$";
	open(TMPFILE,">$TMPFILE");
	print TMPFILE "locked on $hostname by $USER (pid=$$)\n";
	close(TMPFILE);
	for (; $timeout > 0; $timeout -= $SLEEP) {
		last if link($TMPFILE,$LOCKFILE);
		warn "Bahahahahaa - link count is > 2!\n" if (lstat($LOCKFILE))[3] > 2;
		last if (lstat($TMPFILE))[3] == 2;
#		print ".";
		sleep($SLEEP);
	}
        if ($timeout >= 0 && (lstat($TMPFILE))[3] != 2) {
	    warn "boohoo - I don't really have the lock!\n";
	}
	unlink($TMPFILE);
	if ($timeout < 0) {
#		print "failed)\n";
		warn("unable to get lock for problem/request $tolock\n");
		return($LOCK_NOT_OK);
	}else{
#		print " got it!)\n";
		$LOCKS{$tolock}++ if $tries <= 19;
		return($LOCK_OK);
	}
}

#unlocks the entire system (by default) or an individual file
#
sub unlock {
	local($tolock) = @_;
	local($LOCKFILE);
	$LOCKFILE = $tolock;
#	print STDERR "unlocking $LOCKFILE\n";
	if (-f $LOCKFILE) {
		unlink($LOCKFILE);
		delete $LOCKS{$tolock};
	}else{
		warn "$LOCKFILE: lock gone\n";
	}
	return 1;
}

1;
