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

# $Id: attach-2013-10-13-mutt-thread-read.pl,v 1.1 2013/10/13 20:36:51 aehlig Exp $
 
my $statusdir = "/home/aehlig/uucp-batch/AUTOREADTHREAD";
my $batchfile = $statusdir . "/auto";
my $statusfile= "/home/aehlig/conf/mutt-current-folder.txt";

my $folder = `cat \Q$statusfile\E`; chomp($folder);
my $mid;

aquire_lock();

my $time = `date +%s`; chomp($time);
my $hostname = `hostname`; chomp($hostname);
my $uuid = "A-$time.$$-$hostname";

while (<STDIN>) {
	/^Message-I[dD]: <(\S+)>/ and do {
		$mid = $1;
		last;
	};
}

defined $mid 
	or die_gracefully("No message-id found\n");


open(BATCH,">>",$batchfile);

print BATCH "#thread-read $uuid 2\n";
print BATCH "$folder\n";
print BATCH "$mid\n";

close(BATCH);

rmdir "$statusdir/#lock";

print "Thread $mid in folder $folder with all future messages will automatically be marked as read.\n";

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

