#!/usr/bin/perl -w
use strict;

## Send batched files for the given host, according to priorities

my $hostname = shift;

my $targetdir =  '/home/aehlig/uucp-batch/' . $hostname;
my $targetcommand = $hostname . '!uucp-batch-drop-hilbert';


get_lock();

opendir (my $bd, $targetdir) or die_gracefully("Failed to read $targetdir ($?)\n");
my @requests = readdir($bd);
closedir($bd) or die_gracefully("Failed to close $targetdir ($?)");

my $prio;

foreach $prio (@requests) {
	$prio =~ /^[0-9A-Za-z]$/ or next;

	open (UUX, "|-","uux","-","-g",$prio,$targetcommand)
		or die_gracefully("Failed to open uux ($!)");

	open(BATCH,"<", $targetdir . "/" . $prio)
		or die_gracefully("Failed to open $targetdir/$prio ($!)\n");
	while(<BATCH>) {
		print UUX $_;
	};
	close(BATCH)
	or die_gracefully("Failed to close $targetdir/$prio ($!)\n");

	close (UUX)
		or die_gracefully("Failed to close uux ($!)\n");
	
	unlink $targetdir . "/" . $prio;
}

rmdir "$targetdir/#lock";

exit 0;

############################################################################

sub get_lock
{
	my $lock = "$targetdir/#lock";
	my $retries = 30;

	for($retries--;$retries>=0;$retries--) {
		mkdir $lock and return 1;
		print "Failed to create lock $lock ($!)\nWill try another $retries times.\n";
		if ($retries) {
			sleep 2;
			while(int(rand(7))!=0) {
				sleep 1;
			}
		}
	}
	die "Can't optain lock $lock.\n";
}

sub die_gracefully
{
	my ($message) = @_;

	rmdir "$targetdir/#lock";
	die $message;
}

sub contents_of
{
        my ($name) = @_;

        open(FILETOREAD, "< $name")
                or die "Failed to open $name ($!)\n";

        my $contents = do {local $/; <FILETOREAD>};

        close(FILETOREAD)
                or die "Failed to close $name ($!)\n";

        return $contents;
}

