use alienfile;

probe sub { 'share' };

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

  if($^O eq 'MSWin32')
  {
    meta->prop->{env}->{PERL} = '/usr/bin/perl';
  }
  else
  {
    meta->prop->{env}->{PERL} = $^X;
  }

  plugin Download => (
    url => 'http://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' => ( msys_version => '0.08' );
  
  build [
    '%{configure} --disable-shared',
    '%{make}',
    '%{make} install',
  ];
};
