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

configure {
  requires 'Path::Tiny';
};

my $version = $ENV{ALIEN_WASMTIME_VERSION} || 'v0.21.0';
my $arch = 'x86_64';

if($^O eq 'linux')
{
  # archname=x86_64-linux-gnu-thread-multi
  if($Config{archname} =~ /^(x86_64|aarch64)-linux/ && $Config{ptrsize} == 8)
  {
    if($1 eq 'aarch64')
    {
      $arch    = 'aarch64';
    }
  }
  else
  {
    print "Only x86_64 and arm64 are supported on Linux.\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/ || $Config{ptrsize} != 8)
  {
    print "Only x86_64 is supported on Windows.\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 on macOS / darwin\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;
}

probe sub { 'share' };

share {

  if($^O eq 'linux')
  {
    start_url "https://github.com/bytecodealliance/wasmtime/releases/download/$version/wasmtime-$version-$arch-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-$arch-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-$arch-macos-c-api.tar.xz";
    plugin 'Download';
    plugin Extract => 'tar.xz';
  }

  plugin 'Build::Copy';

  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 ";
  };
};


