#!/usr/bin/perl

use strict;
use warnings;
use CDB_File;
use IO::Select;
use Sys::Syslog;

# qmail-quickshunt.pl
# $URL: svn+ssh://fw/repos/code/perl/qmail/qmail-quickshunt.pl $
# $Id: qmail-quickshunt.pl 129 2008-04-20 21:39:22Z ed $
# Copyright (C) 2006, ed neville
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.

openlog( "cdbheaders[$$]", "LOG_PID", "LOG_DAEMON" );

my %config = ( 
	"moved_mail" => 0,
	"bad_exit" => 111,
	"maildir_location" => "/Maildir/",
	"sender" => $ENV{'SENDER'}, 
	"destination" => $ENV{'RECIPIENT'} );

my @input_lines = <STDIN>;
chomp( @input_lines );

sub debug_log {
	my $msg = shift;
	syslog( 'LOG_DEBUG', $msg );
}

sub write_file {
	my $path = shift;

	$path = $ENV{'HOME'} . $path;
	
	my $rand_file_name = "${path}tmp/" . time() . "_" . $$;

	open( F, ">$rand_file_name" )
		or die( "cannot write $rand_file_name:$!" );
	
	foreach( @input_lines ) {
		next if( not defined( $_ ) );
		print( F "$_\n" );
	}
	close(F);

	my $new_path = "${path}new/" . time() . "_" . $$;
	debug_log( "moving to $new_path" );
	rename( $rand_file_name, $new_path )
		or die( "cannot move to $new_path:$!" );
	exit( $config{'moved_mail'} );
}

# this is something that we can do before starting the spam filters
# this enables us to do very neat text based processing on the headers
# rather than passing to maildrop

my $path_to_cdb = "${ENV{'HOME'}}/Maildir/headers.cdb";

if( !-f $path_to_cdb ) {
	$path_to_cdb = "/etc/headers.cdb" if( -f "/etc/headers.cdb" );
	$path_to_cdb = "/usr/local/etc/headers.cdb" if( -f "/usr/local/etc/headers.cdb" );
}


if( -f $path_to_cdb ) {
	my $c = tie( my %cdb_headers, 'CDB_File', $path_to_cdb )
		or die( "cannot open the cdb file $path_to_cdb:$!" );

	if( defined( $cdb_headers{$config{'sender'}} ) ) {
		write_file( $cdb_headers{$config{'sender'}} );
	}

	if( defined( $cdb_headers{'destination'} ) ) {
		write_file( $cdb_headers{'destination'} );
	}

	foreach my $current_line ( @input_lines ) {
		last if( $current_line eq "" );
		
		if( defined( $cdb_headers{$current_line} ) ) {
			#debug_log( "Found matching header: $current_line" );
			write_file( $cdb_headers{$current_line} );
		}
	}
}
else {
	syslog( 'LOG_DEBUG', "missing cdb files" );
}

write_file( $config{'maildir_location'} );

exit(0);

