#!/usr/bin/perl -w
use strict;
use File::Basename;

## add a maildirdiff patch to a batch request using different priorities depending
## on the type of the patch.

my ($patch,$hostname) = @ARGV;

my $targetdir =  '/home/aehlig/uucp-batch/' . $hostname;
my $prio_create = 'L';
my $prio_flags = 'M';
my $prio_delete = 'O';

my %urgentboxes = ('INBOX' => 4, 'otherImportantMailbox' => 4, 'etc' => 4)

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

open(PATCH,"<", $patch)
	or die "Failed to open $patch ($!)\n";

my $id = <PATCH>;
my $mailbox = <PATCH>; chomp($mailbox);
my $command = <PATCH>;

my $linecount = 3;

while(<PATCH>) {
	$linecount++;
};

close(PATCH)
	or die "Failed to close $patch ($!)\n";

my $prio = $prio_flags;

$command =~ /^DELETE/ and $prio = $prio_delete;
$command =~ /^CREATE/ and $prio = $prio_create;

defined($urgentboxes{$mailbox}) and do {
	$prio = chr(ord($prio) - $urgentboxes{$mailbox});
};


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

get_lock();

open(PATCH,"<", $patch)
	or die_gracefully("Failed to open $patch ($!)\n");

open(BATCH,">>","$targetdir/$prio")
	or die_gracefully("Failed to open $targetdir/$prio ($?)\n");

print BATCH "#uucp-drop " . basename($patch) . " $linecount\n";

while(<PATCH>) {
	print BATCH $_;
};

close (BATCH)
	or die_gracefully("Failed to close uux ($!)\n");

close(PATCH)
	or die_gracefully("Failed to close $patch ($!)\n");

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;
}
