#!/usr/bin/perl -w
#----------------------------------------------------------------------
# merge_maildirs: Merge the files between two Maildirs/
#----------------------------------------------------------------------
# Copyright (C) 2006 Gordon Rowell <gordonr@gormand.com.au>
#
# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
#----------------------------------------------------------------------

use strict;
use warnings;

use Getopt::Long;
use File::Copy;

my %options = ();

GetOptions(\%options, 'source=s', 'destination=s');

for my $dir ( qw(source destination) )
{
    die "--$dir argument required" unless $options{$dir};
    die "$dir is not a directory: $!" unless -d $options{$dir};

    die "$dir/new missing: $!" unless -d "$options{$dir}/new";
    die "$dir/cur missing: $!" unless -d "$options{$dir}/cur";
}

die "source and destination must be different\n" 
    if ($options{source} eq $options{destination});

for my $dir ( qw(new cur) )
{
    my $source = "$options{source}/$dir";
    my $dest_new = "$options{destination}/new";
    my $dest_cur = "$options{destination}/cur";

    warn "$source, $dest_new, $dest_cur\n";

    opendir (SOURCE, $source) or
	die"Couldn't opendir $source: $!";

    for my $file ( grep { !/^\./ } readdir SOURCE )
    {
        my $file_root = $file;
        $file_root =~ s/:.*//;

	warn "Examining $source/$file ($file_root)\n";

	if ( -e ("$dest_cur/$file") )
	{
	    warn "DUPLICATE: $source/$file and $dest_cur/$file\n";
	    unlink "$source/$file" or die "Coudn't unlink $source/$file: $!\n";
	    next;
	}

	if ( -e ("$dest_new/$file") )
	{
	    warn "DUPLICATE: $source/$file and $dest_new/$file\n";
	    unlink "$source/$file" or die "Coudn't unlink $source/$file: $!\n";
	    next;
	}

	if ( defined scalar glob("$dest_cur/$file_root*") )
	{
	    warn "MATCH_ROOT: $source/$file_root exists in $dest_cur\n";
	    next;
	}

	if ( defined scalar glob("$dest_new/$file_root*") )
	{
	    warn "MATCH_ROOT: $source/$file_root exists in $dest_new\n";
	    next;
	}

	warn "MOVE: $source/$file $options{destination}/$dir/$file\n";

	move "$source/$file", "$options{destination}/$dir/$file" or
	    die "Couldn't copy $source/$file, $options{destination}/$dir/$file";

    }
}
