#! /usr/bin/perl

use strict;
use warnings;
use Test::More;
use File::Basename;
use FindBin qw($Bin);
use Getopt::Long;
use Pod::Usage;
use if @ARGV > 0   => 'Data::Dumper';
use if $ENV{DEBUG} => 'Smart::Comments';

if (@ARGV) {
    GetOptions(
        'h|help' => sub { pod2usage -exit => 0, -verbose => 1 },
        'm|man'  => sub {
            pod2usage
              -exit      => 0,
              -verbose   => 2,
              -noperldoc => system('perldoc -V 2>/dev/null 1>/dev/null');
        },
      )
      and @ARGV
      or pod2usage;
}

use_ok 'Test::MTA::Exim4' or BAIL_OUT 'Unexpected!!!';
isa_ok my $exim = Test::MTA::Exim4->new => 'Test::MTA::Exim4';

if (@ARGV) {
    foreach my $address (@ARGV) {
        -d ($_ = "$Bin/samples/$address")
          or mkdir $_
          or -d "$Bin/samples"
          ? die "Can't create $_: $!\n"
          : "$Bin/samples directory missing\n";

        my $outfile = "$_/-bt";

        $_ = $exim->_run_exim_bt($address);
        open(my $f, '>', $outfile) or die "$0: Can't open $outfile: $!\n";
        ok print({$f} (Data::Dumper->Dump([$_], ['bt']))),
          "data for $address written";
    }

    done_testing;
    exit;
}

foreach (grep { -f "$_/-bt" } glob "$Bin/samples/*") {
    my $address = basename $_;
    my $bt      = do "$_/-bt";
    my @target;
    foreach (map { values %$_ } grep { ref } values %$bt) {
        delete $_->{data};
        delete $_->{original};
        push @target, $_;
    }
    $exim->routes_as_ok($address, \@target, $address);
}

done_testing;

=head1 NAME

 10-routing.t - automated tests with Test::MTA::Exim4

=head1 SYNOPSIS

 # learn mode
 DIRECTORY/10-routing.t ADDRESS...

 # test mode
 DIRECTORY/10-routing.t
 prove [DIRECTORY]

=head1 AUTHOR

Heiko Schlittermann L<hs@schlittermann.de>

=cut

