package ProFTPD::Tests::Config::IfModule;

use lib qw(t/lib);
use base qw(ProFTPD::TestSuite::Child);
use strict;

use File::Spec;
use IO::Handle;

use ProFTPD::TestSuite::FTP;
use ProFTPD::TestSuite::Utils qw(:auth :config :running :test :testsuite);

$| = 1;

my $order = 0;

my $TESTS = {
  ifmodule_close_extra_args => {
    order => ++$order,
    test_class => [qw(forking)],
  },

};

sub new {
  return shift()->SUPER::new(@_);
}

sub list_tests {
  return testsuite_get_runnable_tests($TESTS);
}

sub ifmodule_close_extra_args {
  my $self = shift;
  my $tmpdir = $self->{tmpdir};
  my $setup = test_setup($tmpdir, 'config');

  my $config = {
    PidFile => $setup->{pid_file},
    ScoreboardFile => $setup->{scoreboard_file},
    SystemLog => $setup->{log_file},

    AuthUserFile => $setup->{auth_user_file},
    AuthGroupFile => $setup->{auth_group_file},
    AuthOrder => 'mod_auth_file.c',

    IfModules => {
      'mod_delay.c' => {
        DelayEngine => 'off',
      },
    },
  };

  my ($port, $config_user, $config_group) = config_write($setup->{config_file},
    $config);

  if (open(my $fh, ">> $setup->{config_file}")) {
    print $fh <<EOC;
<IfModule mod_xfer.c>
  TransferLog /dev/null

# NOTE: This </IfModule> with the module name should cause the parser to
# fail; it is unexpected input.
</IfModule mod_xfer.c>
EOC
    unless (close($fh)) {
      die("Can't write $setup->{config_file}: $!");
    }

  } else {
    die("Can't open $setup->{config_file}: $!");
  }

  my $ex;

  eval { server_start($setup->{config_file}, $setup->{pid_file}) };
  unless ($@) {
    $ex = 'Server started up unexpectedly';

    # Allow server to finish starting up
    sleep(1);
    eval { server_stop($setup->{pid_file}) };

    test_cleanup($setup->{log_file}, $ex);
    die($ex);
  }

  test_cleanup($setup->{log_file}, $ex);
}

1;
