#!/usr/bin/perl -w

use strict;

my $statusdir = "/home/aehlig/uucp-drop/AUTOREADTHREAD";
my $conffile = $statusdir . "/.muttrc-autoread";
my $toreaddir = $statusdir . "/drop";

############### End of configuration

my %foldertasks = ();

aquire_lock();

opendir my $dir, $toreaddir
	or die_gracefully("failed to open $toreaddir ($!)\n");

my @TASKS = readdir $dir;

closedir $dir;

foreach(@TASKS) {
	/^A-/ or next;

	open(FILE,"<","$toreaddir/$_")
		or die_gracefully("failed to read $toreaddir/$_ ($!)\n");
	my $folder = <FILE>; chomp($folder);
	my $mid = <FILE>; chomp($mid);
	close(FILE);

	$folder =~ /^[a-zA-Z0-9][a-zA-Z0-9-.]*$/ or next;
	$mid =~ /^[a-zA-Z0-9]/ or next;
	$mid =~ s/[^a-zA-Z0-9]/./g;

	defined($foldertasks{$folder})
		or $foldertasks{$folder} = "c=$folder<enter>";

	$foldertasks{$folder} .= "/~i $mid<enter>";
	$foldertasks{$folder} .= "<read-thread>";
	
}

open(MUTTRC,">",$conffile)
	or die_gracefully("failed to open $conffile ($!)\n");

print MUTTRC "source /home/aehlig/conf/muttrc-base\n";

print MUTTRC "push \"";
foreach(keys(%foldertasks)) {
	print MUTTRC $foldertasks{$_};
}

print MUTTRC "c=INBOX<enter><quit>\"\n";

close MUTTRC
	or die_gracefully("Failed to close $conffile ($!)\n");

system "mutt", "-F", $conffile, "-f", "/home/aehlig/MAIL/INBOX";

rmdir "$statusdir/#lock";

exit 0;

############### End of main

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

	print $message;
	rmdir "$statusdir/#lock";
	exit 1;
}

sub aquire_lock {
	for (1..10) {
		mkdir "$statusdir/#lock" and return;
		sleep(rand(60));
	}
	die "Failed to create lock in directory $statusdir ($!)\n";
}
