#!/usr/bin/perl
#
# $Id$
#
use strict;
use Getopt::Std;
use File::Copy;
use File::Find;

my $version = '2.10.2';

my %opts;
getopts('hdse:i:',\%opts);

my $emldir      = $opts{e};
my $inboxdir    = $opts{i}  || '/srv/benno/inbox';
my $dry_run     = $opts{d};
my $symlink     = $opts{s};

help_exit($version) if $opts{h};
help_exit($version) if not ($emldir);

die "Directory \"$inboxdir\" does not exist.\n" unless -d $inboxdir;

use warnings;
my $options;
$options->{wanted}      = \&process_archive;
$options->{no_chdir}    = 1;
find($options, ($emldir));


### SUBS ####

### process_archive
sub process_archive
{
    my $filename = $File::Find::name;
    my $dirname  = $File::Find::dir;
    if ($filename eq $dirname)  { return undef; }     # directory
    if ($filename !~ /\.eml$/)  { return undef; }     # not an eml file

    my $emlfile = $filename;
    eval {
        process_file($filename,$emldir,$inboxdir);
    };
    if ($@) {
        print STDERR $@;
    }
}


### process_file
sub process_file
{
    my ($emlfile,$emldir,$inboxdir) = @_;

    (my $emlbase   = $emlfile) =~ s/^$emldir\/?//;
    (my $inboxfile = $emlbase) =~ s/\//_/g;
    $inboxfile = $inboxdir.'/'.$inboxfile;
    $inboxfile =~ s!//!!g;

    if ($symlink) {
        if (!symlink $emlfile, $inboxfile) {
            die "Cannot symlink $emlfile to $inboxfile: $!\n";
        }
        print "Symlink $emlfile to $inboxfile\n";
        return;
    }

    if (link $emlfile, $inboxfile) {
        print "Link $emlfile to $inboxfile\n";
        return;
    }
    else {
        if(copy($emlfile, $inboxfile)) {
            print "Copy $emlfile to $inboxfile\n";
            return;
        }
        else {
            die "Cannot copy $emlfile to $inboxfile: $!\n";
        }
    }
}


### help_exit()
sub help_exit
{
    my $version = shift;

    my ($basename) = $0 =~ m!.*?([^/]+?)$!;
    print "$basename version $version\n";
    print "Usage: $basename [-h] -s -a <archive directory> [-i <inbox directory>]\n";
    print "    -i <inbox>           inbox directory (default: /srv/benno/inbox)\n";
    print "    -e <emldirectory>    directory structure with eml files\n";
    print "    -s                   symlink instead of copy files\n";
    print "\n";
    
    exit 1;
}
