use alienfile;

probe sub { 'share' };

share {
  requires 'Alien::autoconf' => '0.05';
  requires 'Alien::m4'       => '0.11';
  requires 'Path::Tiny'      => '0.077';

  meta->prop->{env}->{PERL} = $^X unless $^O eq 'MSWin32';

  plugin Download => (
    url => 'ftp://ftp.gnu.org/gnu/automake',
    filter => qr/^automake-.*\.tar\.gz$/,
    version => qr/([0-9\.]+)/,
  );
  plugin Extract => 'tar.gz';
  
  patch sub {
    my($build) = @_;

    # https://debbugs.gnu.org/cgi/bugreport.cgi?bug=20903
    # bug in automake: it puts the @datadir@ in double quotes
    # in one place in bin/aclocal, which causes Perl to barf
    # if prefix has an at sign (@) in it.  This is commonly
    # the case when using perlbrew.    
    Path::Tiny->new('bin/aclocal.in')->edit_lines(sub {
      s/"\@datadir\@/'\@datadir\@'."/g;
    });
    
    my @in = grep { $_->basename =~ /\.in$/ } Path::Tiny->new('bin')->children;
    push @in, Path::Tiny->new('lib/Automake/Config.in');
    
    foreach my $in (@in)
    {
      $in->copy($in->sibling($in->basename . '~'));
      my($shebang, @lines) = $in->lines;

      my @preamble = ($shebang);
      while(defined $lines[0] && $lines[0] =~ /^#/)
      {
        push @preamble, shift(@lines);
      }

      s/'\@datadir\@(.*?)'/"\$ENV{ALIEN_AUTOMAKE_ROOT}\/share$1"/g for @lines;
      @lines = (
        "BEGIN {\n",
        "  use strict;\n",
        "  use warnings;\n",
        "  use File::Spec;\n",
        "  my(\$v,\$d) = File::Spec->splitpath(File::Spec->rel2abs(__FILE__));\n",
        "  my \@d = File::Spec->splitdir(\$d);\n",
        "  pop \@d for 1..2;\n",
        "  \$ENV{ALIEN_AUTOMAKE_ROOT} ||= File::Spec->catpath(\$v,File::Spec->catdir(\@d), '');\n",
        "}\n",
        @lines,
      );
      $in->spew(@preamble, @lines);
    }
  };
  
  plugin 'Build::Autoconf' => ();
  
  requires 'IPC::Cmd';
  requires 'Capture::Tiny';
  requires 'Path::Tiny';
  
  meta->around_hook(build => sub {
    my($orig, $build, @rest) = @_;

    my $autoconf_bin = IPC::Cmd::can_run('autoconf');
    print "***************************************************\n";
    print "autoconf path = @{[ defined $autoconf_bin ? $autoconf_bin : 'undef' ]}\n";
    if($autoconf_bin)
    {
      my($version) = Capture::Tiny::capture_merged(sub {
        system $autoconf_bin, '--version';
      });
      print "[version]\n";
      print "$version\n";
    }
    print "***************************************************\n";
     my $ret = eval { $orig->($build, @rest) };
    print "***************************************************\n";
    my $log = Path::Tiny->new('config.log');
    if(-f $log)
    {
      print $log->slurp;
    }
    else
    {
      print "no config.log\n";
    }
    print "***************************************************\n";

    my $error = $@;
    if(my $error = $@)
    {
      die $error;
    }
    $ret;
  });
  
  build [
    '%{configure} --disable-shared',
    '%{make}',
    '%{make} install',
  ];
};
