require "bundler/gem_tasks"
require "rubygems/package_task"
require "rake/testtask"

rcd_test_spec = Bundler.load_gemspec("rcd_test.gemspec")

if RUBY_ENGINE == "jruby"
  require "rake/javaextensiontask"

  Rake::JavaExtensionTask.new("rcd_test_ext", rcd_test_spec) do |ext|
    ext.ext_dir = 'ext/java'
    ext.lib_dir = 'lib/rcd_test'
  end
else
  require "rake/extensiontask"

  exttask = Rake::ExtensionTask.new('rcd_test_ext', rcd_test_spec) do |ext|
    ext.ext_dir = 'ext/mri'
    ext.lib_dir = 'lib/rcd_test'
    ext.cross_compile = true
    ext.cross_platform = %w[
      aarch64-linux
      aarch64-linux-gnu
      aarch64-linux-musl
      aarch64-mingw-ucrt
      arm-linux
      arm-linux-gnu
      arm-linux-musl
      arm64-darwin
      x64-mingw-ucrt
      x64-mingw32
      x86-linux
      x86-linux-gnu
      x86-linux-musl
      x86-mingw32
      x86_64-darwin
      x86_64-linux
      x86_64-linux-gnu
      x86_64-linux-musl
    ]
  end
end

namespace "gem" do
  if exttask
    task 'prepare' do
      require 'rake_compiler_dock'
      require 'io/console'
      sh "bundle package"
      sh "mkdir -p tmp/gem"
      sh "cp ~/.gem/gem-*.pem tmp/gem/ || true"
      unless ENV['CI']
        ENV["GEM_PRIVATE_KEY_PASSPHRASE"] = STDIN.getpass("Enter passphrase of gem signature key: ")
      end
    end

    exttask.cross_platform.each do |plat|
      desc "Build all native binary gems"
      multitask 'native' => plat

      desc "Build the native gem for #{plat}"
      task plat => 'prepare' do
        config = "-- #{ENV['RCD_TEST_CONFIG']}"
        # Set mountdir of the directory where .git resides,
        # - so that git ls-files in the gemspec works
        # - and to bundle the rake-compiler-dock under test
        RakeCompilerDock.sh <<-EOT, platform: plat, mountdir: Dir.pwd + "/../..", verbose: true
          (cp tmp/gem/gem-*.pem ~/.gem/ || true) &&
          bundle install --local &&
          rake native:#{plat} pkg/#{exttask.gem_spec.full_name}-#{plat}.gem "MAKE=make V=1" #{config}
        EOT
      end
    end
  end

  desc "Build a jruby gem"
  task "jruby" do
    require 'rake_compiler_dock'
    sh "bundle package"
    RakeCompilerDock.sh <<-EOT, rubyvm: "jruby", platform: "jruby", mountdir: Dir.pwd + "/../..", verbose: true
      mvn archetype:generate -DartifactId=test -DarchetypeVersion=1.4 -DinteractiveMode=false -DgroupId=test -Dpackage=test &&
      bundle install --local &&
      bundle exec rake java gem
    EOT
  end
end

Rake::TestTask.new(:test) do |t|
  t.libs << "test"
  t.libs << "lib"
  t.test_files = FileList["test/**/test_*.rb"]
end

task default: [:clobber, :compile, :test]
task gem: :build

CLEAN.add("{ext,lib}/**/*.{o,so}", "pkg", "tmp")
