#! /usr/bin/env bash
#
#  script to test a set of gem files
#  - test-gem-file-contents
#  - conditionally, if the local system can do it, test-gem-installation
#
set -o errexit
set -o pipefail

ruby="ruby@latest"
gem_platform_local=`ruby -e "puts Gem::Platform.local.to_s"`

function remove_all_nokogiris {
  yes | mise x $ruby -- gem uninstall --force nokogiri || true
}

function install_and_test {
  gem=$1
  if [[ $gem =~ "java" ]] ; then
    ruby="ruby@jruby"
  else
    ruby="ruby@latest"
  fi
  remove_all_nokogiris
  mise x $ruby -- gem install --local $gem
  mise x $ruby -- ./scripts/test-gem-installation

  if [[ $gem =~ nokogiri-[^-]*\.gem ]] ; then
    remove_all_nokogiris
    NOKOGIRI_USE_SYSTEM_LIBRARIES=t mise x $ruby -- gem install --local $gem
    mise x $ruby -- ./scripts/test-gem-installation
  fi
}

gems=$*

for gem in $gems ; do
  mise x $ruby -- ./scripts/test-gem-file-contents $gem
done

for gem in $gems ; do
  if [[ $gem =~ nokogiri-[^-]+(-(${gem_platform_local}|java))?\.gem$ ]] ; then
    install_and_test $gem
  fi
done
