#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use Test::More;
use Test::Command::Simple;
use Path::Tiny qw(path cwd);
use Cwd;

my $mb2md = $ENV{MB2MD} || 'md2md';

my $output_template       = path('debian/tests/data/example.output')->slurp;
my $tempdir               = Path::Tiny->tempdir();
my $fakehome = $ENV{HOME} = "$tempdir/home";
my $dir1                  = "$tempdir/1";
my $dir2                  = "$tempdir/2";

foreach my $dir ($fakehome, $dir1, $dir2) {
    ok(path($dir)->mkpath, "Created '$dir'");
    is(ref(path('debian/tests/data/example.mbox')->copy("$dir/")),
       'Path::Tiny',
       "Successfully copied example.mbox to fake home directory $dir/");
}

sub replace_prefix {
    my ($string, $prefix) = @_;
    $prefix .= '/' if ($prefix ne '' and $prefix !~ m(/$));
    $string =~ s:<prefix>/:$prefix:g;
    return $string;
}

# Without prefix, i.e. relative to $HOME
run_ok("$mb2md -s example.mbox -d example.maildir");
is(stdout, replace_prefix($output_template, $fakehome), 'Stdout as expected ($HOME)');
is(stderr, '', 'No stderr ($HOME)');
is(0+path("$fakehome/example.maildir/cur")->children, 2, '2 mails in maildir ($HOME)');

# With absolute paths
run_ok("$mb2md -s $dir1/example.mbox -d $dir1/example.maildir");
is(stdout, replace_prefix($output_template, $dir1),
   'Stdout as expected (/…)');
is(stderr, '', 'No stderr (/…)');
is(0+path("$dir1/example.maildir/cur")->children, 2, '2 mails in maildir (/…)');

# With ./ prefix
my $cwd = cwd;
ok(chdir($dir2), "Change to directory '$dir2'.");
run_ok("$mb2md -s ./example.mbox -d ./example.maildir");
ok(chdir($cwd), "Change to directory back to '$cwd'.");
is(stdout, replace_prefix($output_template, '.'), 'Stdout as expected (./…)');
is(stderr, '', 'No stderr (./…)');
is(0+path("$dir2/example.maildir/cur")->children, 2, '2 mails in maildir (./…)');

done_testing();
