package App::EzPz::TestSetup;

use IO::All;
use IPC::System::Simple qw(run);
use Cwd;
use Exporter;
use strictures 1;

our @EXPORT = qw(create_install create_list);

sub create_install {
  die "Usage: ezpz-create-test-ezmlm-install ezmlm-source.tgz build-dir install-dir"
    unless @_ == 3;
  
  my ($ezmlm_tarball_path, $build_dir_path, $install_to_path) = @ARGV;
  
  my $ezmlm_tarball = io->file(io->file($ezmlm_tarball_path)->rel2abs);
  
  my $orig_cwd = io->dir(cwd);
  
  my $build_dir = io->dir($build_dir_path)->absolute;
  my $install_to = io->dir($install_to_path)->absolute;
  
  unless ($build_dir->exists) {
    $build_dir->mkpath;
    $build_dir->chdir;
    run 'tar', 'xzf', $ezmlm_tarball;
    $orig_cwd->chdir;
  }
  
  my ($src_dir) = ($build_dir->all_dirs)[0];
  
  die "No source dir found in ${build_dir}" unless $src_dir;
  
  foreach my $type (qw(bin etc lib man qmail)) {
    $src_dir->catfile("conf-${type}")->print($install_to->catdir($type)."\n");
  }
  
  $src_dir->chdir;
  
  run make => 'clean';
  run 'make';
  run make => 'man';
  run './ezmlm-test';
  $install_to->catdir('bin')->mkpath;
  run make => 'install';
}

sub create_list {
  die "Usage: ezpz-create-test-ezmlm-list ezmlm-bindir list-base-dir list-name"
    unless @_ == 3;
  
  my ($ezmlm_bin_path, $list_base_path, $list_name) = @_;
  
  my $ezmlm_bin = io->dir($ezmlm_bin_path)->absolute;
  
  my $list_base = io->dir($list_base_path)->absolute;
  
  run(
    $ezmlm_bin->catfile('ezmlm-make'),
    $list_base->catdir($list_name),
    $list_base->catfile("dot-qmail-for-${list_name}"),
    $list_name,
    'example.com'
  );
