# -*- cperl -*-

use 5.10.0;

use ExtUtils::testlib;
use Test::More ;
use Test::Memory::Cycle;
use Config::Model ;
use Log::Log4perl qw(:easy) ;
use Path::Tiny ;
use Test::Warn ;
use Test::Exception ;

use warnings;

use strict;

eval { require AptPkg::Config ;} ;
if ( $@ ) {
    plan skip_all => "AptPkg::Config is not installed";
}
elsif ( -r '/etc/debian_version' ) {
    plan tests => 25;
}
else {
    plan skip_all => "Not a Debian system";
}

my $arg = shift ;
$arg = '' unless defined $arg ;

my ($log,$show) = (0) x 2 ;
my $do ;

my $trace = $arg =~ /t/ ? 1 : 0 ;
$log                = 1 if $arg =~ /l/;
$show               = 1 if $arg =~ /s/;
$do                 = $1 if $arg =~ /(\d+)/;

my $home = $ENV{HOME} || "";
my $log4perl_user_conf_file = "$home/.log4config-model";

if ($log and -e $log4perl_user_conf_file ) {
    Log::Log4perl::init($log4perl_user_conf_file);
}
else {
    Log::Log4perl->easy_init($log ? $WARN: $ERROR);
}

my $model = Config::Model -> new ( ) ;

Config::Model::Exception::Any->Trace(1) if $arg =~ /e/;

ok(1,"compiled");

# pseudo root where config files are written by config-model
my $wr_root = path('wr_root');

# cleanup before tests
$wr_root->remove_tree if $wr_root->exists;
$wr_root->mkpath() ;

my $dpkg = $model->instance(
    root_class_name => 'Dpkg',
    root_dir        => $wr_root->stringify,
);

my $root = $dpkg->config_root ;
$dpkg->initial_load_stop;

my $opt = 'config\..*|configure|.*Makefile.in|aclocal.m4|\.pc' ;

# load mandatory values otherwise the exits on error during next test
$root->load("control source Maintainer=foo\@bar.com");

my @test = (
    [ "clean=foo,bar,baz",           'clean',         "foo\nbar\nbaz\n" ],
    [ 'source format="3.0 (quilt)"', 'source/format', "3.0 (quilt)\n" ],
    [
        qq!source options extend-diff-ignore="$opt"!, 'source/options',
        qq!extend-diff-ignore="$opt"\n!
    ],
);

my %files ;
foreach my $t (@test) {
    my ($load, $file, $content) = @$t ;
	$files{$file} = $content if $file;

	print "loading: $load\n" if $trace ;
	$root->load($load) ;

	$dpkg->write_back ;

	foreach my $f (keys %files) {
	    my $test_file = $wr_root->child('debian')->child($f) ;
	    ok($test_file->is_file ,"check that $f exists") ;
		my @lines = grep { ! /^#/ and /\w/ } $test_file->lines ;
		is(join('',@lines),$files{$f},"check $f content") ;
	}
}

$root->load('control source Maintainer="foo <foo@bar>" ! my_config dependency-filter=lenny') ;
is($root->grab_value("my_config package-dependency-filter:foopkg"),
    'lenny', "check package-dependency-filter");

warning_is {
    my $ts = $root->grab_value("control source Testsuite");
}  undef, 'check that Testsuite does not warn for random maintainer ';

warning_like {
    $root->load('control source Testsuite=autopkgtest-foobar');
} qr/unknown value/i, "check that a warning is emitted for unknown Testsuite value";

my @teams = (
    'Debian Perl Group <pkg-perl-maintainers@lists.alioth.debian.org>',
    'Debian Ruby Extras Maintainers <pkg-ruby-extras-maintainers@lists.alioth.debian.org>',
);

foreach my $team (@teams) {
    # reset testsuite values, maintainer cannot be null, so use John Doe instead
    # of a packaging team that triggers a special behavior
    $root->load('control source Maintainer="John Doe <john@doe.com>" Testsuite~') ;
    my ($str) = ($team =~ /pkg-(perl|ruby)/);
    my $target =  "autopkgtest-pkg-$str";

    $root->load(qq!control source Maintainer="$team"!);
    is($root->grab_value("control source Testsuite"), undef,'check Testsuite default value');
    $root->grab('control source Testsuite')->apply_fixes;

    is($root->grab_value("control source Testsuite"), $target,"check Testsuite $str output");
}

# perl vs ruby, requires that loop above does not finish with perl team
warning_like {
    $root->load('control source Testsuite=autopkgtest-pkg-perl');
} qr/maintainer team/i, "check that a warning is emitted for Testsuite value mistmatch";


my $lic_text = $root->grab(steps => "copyright License:FooBar text", check => 'no');
is($lic_text->fetch, undef, "test unknown lic text") ;

say "store lic_text" if $trace ;
$lic_text->store("yada yada");

say "test stored lic_text" if $trace ;
is($lic_text->fetch, 'yada yada', "test specified lic text") ;

my $lic_gpl = $root->grab(step => "copyright License:GPL-1 text", check => 'no');
like($lic_gpl->fetch,qr!/usr/share/common-licenses/GPL-1!
     , "retrieved license text summary") ;

memory_cycle_ok($model, "check memory cycles");
