#!/usr/bin/perl

use strict;
use warnings;

# $Id$
# $URL$
# 
# short program to deliver mail to PROPER maildir format and not the mbox 
# rubbish we're currently putting up with.
# reprocessing these files using imap is expensive work. using maildir 
# should reduce the imap usage

sub make_dir {
	my $dir = shift;

	mkdir( $dir )
		or eval {
			my $error = "cannot create directory $dir: $!";
			log_error( $error );
			die( $error );
		};
}

sub check_mail_dir_exists {
	my $path = shift;
	
	my @paths = ["", "/cur", "/new", "/tmp" ];

	foreach( @paths ) {
		my $p = $path . $_;
		if( ! -d "$p" ) {			
			make_dir( $p );
		}
	}
}

my %msg_details;

open( LOG, ">>log" )
	or exit;
print( LOG "\n\n", scalar( localtime() ), "\n" );
foreach( sort keys( %ENV ) ) {
	print( LOG "$_\t${ENV{$_}}\n" );
}

foreach( @ARGV ) {
	print( LOG "ARGV: $_\n" );
}

my @lines = <STDIN>;

my $fn = sprintf( "%d_%d_%d", time(), int( rand( 65535 ) ), $$ );
my $tmp_name = "tmp/$fn";
my $new_name = "new/$fn";


print( LOG $tmp_name, "\n" );
print( LOG $new_name, "\n" );

foreach( @lines ) {

	if( $_ =~ /^Subject: (.*)/ ) {
		$msg_details{'subject'} = $1;
	}

	if( $_ =~ /^Sender: (.*)/ ) {
		$msg_details{'sender'} = $1;
	}

	last if( $_ =~ /^$/ );
}

my $dest = "Maildir";

foreach( sort keys( %msg_details ) ) {
	print( LOG "$_ ${msg_details{$_}}\n" );
}

check_mail_dir_exists( $dest );

open( MAIL, ">$dest/$tmp_name" ) or
	die( "cannot put file in $tmp_name:$!" );
print( MAIL @lines );
close( MAIL );

rename( "$dest/$tmp_name", "$dest/$new_name" );

close( LOG );


