use alienfile;
use Path::Tiny qw( path );

plugin 'Probe::CBuilder' => (
  libs    => '-lbz2',
  version => qr/version = '(.*?)[,']/,
  program => q{
#include <bzlib.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
  printf("version = '%s'\n", BZ2_bzlibVersion());
  return 0;
}
},
);

plugin 'Probe::CommandLine' => (
  command   => 'bzip2',
  secondary => 1,
);

share {

  plugin 'Build::MSYS' => ();
  plugin 'Download' => (
    url     => 'http://www.bzip.org/downloads.html',
    version => qr/^bzip2-([0-9\.]+)tar.gz$/,
  );
  plugin Extract => 'tar.gz';
  
  if($^O eq 'MSWin32')
  {
    requires 'Path::Tiny' => '0.077';
    patch sub {
      path('Makefile')->edit_lines(sub {
        s/(\Qchmod a+x\E.*?(bzip2|bunzip2|bzcat|bzip2recover))$/ $1 . '$(EXE)' /eg;
      });
      path('bzlib.h')->edit_lines(sub {
        if(/WINAPI func/)
        {
          $_ = join('', "#   ifdef BZ_STATIC\n",
                        "#   define BZ_API(func) func\n",
                        "#   else\n",
                        $_,
                        "#   endif\n");
        }
      });
    };
  }
  
  build [
    [ '%{make}', 'all', "CC=%{perl.config.cc}", "CFLAGS=%{perl.config.cccdlflags} %{perl.config.optimize}", ],
    [ '%{make}', 'install', 'PREFIX=%{alien.install.prefix}', 'EXE=%{perl.config.exe_ext}' ],
    sub {
      my($build) = @_;
      my($version) = path(".")->absolute->basename =~ /([0-9\.]+)$/;
      $build->runtime_prop->{version} = $version;
    },
  ];
  gather sub {
    my($build) = @_;
    my $prefix = $build->runtime_prop->{prefix};
    $build->runtime_prop->{cflags}        = "-I$prefix/include ";
    $build->runtime_prop->{cflags_static} = "-I$prefix/include ";
    $build->runtime_prop->{cflags_static} .= ' -DBZ_STATIC=1' if $^O eq 'MSWin32';
    $build->runtime_prop->{libs}          = "-L$prefix/lib -lbz2 ";
    $build->runtime_prop->{libs_static}   = "-L$prefix/lib -lbz2 ";
  };

};
