use alienfile;

plugin 'PkgConfig' => (
  pkg_name => 'libarchive',
  minimum_version => '3.0.0',
);

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

int main(int argc, char *argv[])
{
  int r;
  archive_read a;
  
  a = archive_read_new();
  if(a == NULL)
    return 2;
  
  r = archive_read_free(a);
  if(r != ARCHIVE_OK)
    return 2;
  
  printf("version = '%s'\n", ARCHIVE_VERSION_ONLY_STRING);
  return 0;
}
},
);

share {

  requires 'Env::ShellWords' => '0.01';

  plugin Download => (
    url     => 'http://libarchive.org',
    #url     => 'file:///Users/ollisg/opt/libarchive/3.3.1/src/',
    version => qr/^libarchive-([0-9\.]+)\.tar\.gz$/,
  );

  plugin Extract => 'tar.gz';

  # TODO: lz4 https://github.com/lz4/lz4/releases 
  # TODO: http://zlib.net/
  plugin 'Build::SearchDep' => (
    aliens => [ qw( Alien::Nettle Alien::xz Alien::LZO Alien::Libbz2 Alien::Libxml2 ) ],
  );

  plugin 'Build::Autoconf' => ();

  my $configure_flags = '--with-lzo2';
  $configure_flags .= ' --without-iconv' if $^O eq 'darwin';  
  build [
    "%{configure} --disable-shared --enable-static $configure_flags",
    '%{make}',
    '%{make} install',
  ];
  
  ffi {
    build [
      "%{configure} --enable-shared --disable-static --libdir=%{.install.autoconf_prefix}/dynamic $configure_flags",
      '%{make}',
      '%{make} install',
    ];
  };  
};

if($^O eq 'netbsd')
{
  meta->after_hook(
    gather_system => sub {
      my($build) = @_;
      foreach my $flag (qw( libs libs_static))
      {
        if(defined $build->runtime_prop->{$flag} && $build->runtime_prop->{$flag} =~ m{-L/usr/pkg/lib})
        {
          $build->runtime_prop->{$flag} = '-Wl,-rpath,/usr/pkg/lib ' . $build->runtime_prop->{$flag};
        }
      }
    },
  );
}
