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

if($^O eq 'linux')
{
  # archname=x86_64-linux-gnu-thread-multi
  if($Config{archname} !~ /^x86_64-linux/)
  {
    print "Only x86_64 is supported.\n";
    print "If we are missing a binary tarball that could work for your platform, please comment here:\n";
    print "https://github.com/perlwasm/Alien-wasmtime/issues/2\n";
    exit;
  }
}
elsif($^O eq 'MSWin32')
{
  if($Config{archname} !~ /^MSWin32-x64/)
  {
    print "Only x86_64 is supported.\n";
    print "If we are missing a binary tarball that could work for your platform, please comment here:\n";
    print "https://github.com/perlwasm/Alien-wasmtime/issues/2\n";
    exit;
  }
}
elsif($^O eq 'darwin')
{
  if($Config{myarchname} !~ /^i386-darwin/ || $Config{ptrsize} != 8)
  {
    print "Only x86_64 is supported.\n";
    print "If we are missing a binary tarball that could work for your platform, please comment here:\n";
    print "https://github.com/perlwasm/Alien-wasmtime/issues/2\n";
    exit;
  }
}
else
{
  print "Operating system not supported.\n";
  print "If we are missing a binary tarball that could work for your platform, please comment here:\n";
  print "https://github.com/perlwasm/Alien-wasmtime/issues/2\n";
  exit;
}

configure { requires 'Path::Tiny' };

probe sub { 'share' };

share {

  my $version = $ENV{ALIEN_WASMTIME_VERSION} || 'v0.15.0';

  if($^O eq 'linux')
  {
    start_url "https://github.com/bytecodealliance/wasmtime/releases/download/$version/wasmtime-$version-x86_64-linux-c-api.tar.xz";
    plugin 'Download';
    plugin Extract => 'tar.xz';
  }
  elsif($^O eq 'MSWin32')
  {
    start_url "https://github.com/bytecodealliance/wasmtime/releases/download/$version/wasmtime-$version-x86_64-windows-c-api.zip";
    plugin 'Download';
    plugin Extract => 'zip';
  }
  elsif($^O eq 'darwin')
  {
    start_url "https://github.com/bytecodealliance/wasmtime/releases/download/$version/wasmtime-$version-x86_64-macos-c-api.tar.xz";
    plugin 'Download';
    plugin Extract => 'tar.xz';
  }

  if($^O ne 'MSWin32')
  {
    build [
      'cp -r * %{.install.stage}',
    ];
  }
  else
  {
    build sub {
      my($build) = @_;
      my $stage = path($build->install_prop->{stage})->canonpath;
      $build->system("xcopy . $stage /E");
    };
  }

  gather sub {
    my($build) = @_;
    $build->runtime_prop->{version} = $version;
    $build->runtime_prop->{version} =~ s/^v//;
    $build->runtime_prop->{cflags}  = "-I@{[ $build->runtime_prop->{prefix} ]}/include ";
    $build->runtime_prop->{libs}    = "-L@{[ $build->runtime_prop->{prefix} ]}/lib -lwasmtime ";
  };
};


