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 => 'https://ftp.gnu.org/gnu/automake',
    filter => qr/^automake-.*\.tar\.gz$/,
    version => qr/([0-9\.]+)/,
  );
  plugin Extract => 'tar.gz';

  patch sub {
    my($build) = @_;

    # https://git.savannah.gnu.org/cgit/automake.git/commit/configure.ac?id=ccb57553e3433df3e52e534e6f87915db23ff9a5
    Path::Tiny->new('configure')->edit_lines(sub {
      my $replace = <<'EOF';
printf '%s\n' > conftest/conftest.ac \
  'AC''_INIT([smoke-test], [1])' \
  'AC''_OUTPUT'
EOF
      s{echo 'AC''_INIT' > conftest/conftest.ac}{$replace};
      $replace = <<'END_OF_PATCH';
printf '%s\n' > conftest/conftest.ac \
  'AC'"_PREREQ([$required_autoconf_version])" \
  'AC''_INIT([smoke-test], [1])' \
  'AC''_OUTPUT'
END_OF_PATCH
      s{echo 'AC'"_PREREQ\(\[\$required_autoconf_version\]\)" > conftest/conftest.ac}{$replace};
    });
    Path::Tiny->new('configure')->chmod(0755);

    # 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',
  ];
};
