#! /usr/bin/env bash
#
#  script to run tests on all relevant rubies, and valgrind on supported rubies.
#  outputs tests to `test.log` and valgrind output to `valgrind.log`.
#
#  requires `rvm` to be installed. sorry about that, multiruby dudes.
#
#  it's worth periodically using hoe-debugger's ability to generate
#  valgrind suppression files to remove spurious valgrind messages
#  (e.g., 1.9.3's glob_helper). ["rake test:valgrind:suppression"]
#

# I'd add rubinius, but rvm errors when building it on my machine. :(
RUBIES="\
  ruby-2.4 \
  ruby-2.3 \
  ruby-2.2 \
  ruby-2.1 \
  jruby-9.1.6.0 \
  jruby-1.7.19
  "

TEST_LOG=test.log
VALGRIND_LOG=valgrind.log

# make sure we can test with libxml-ruby installed
export BUNDLE_GEMFILE="$(pwd)/Gemfile_test_all"
cat > $BUNDLE_GEMFILE <<EOF
gem "libxml-ruby", :platform => :mri, :require => false
eval_gemfile File.join(File.dirname(ENV['BUNDLE_GEMFILE']),"Gemfile")
EOF

# Load RVM into a shell session *as a function*
if [[ -s "$HOME/.rvm/scripts/rvm" ]] ; then
    source "$HOME/.rvm/scripts/rvm"
elif [[ -s "/usr/local/rvm/scripts/rvm" ]] ; then
    source "/usr/local/rvm/scripts/rvm"
else
    echo "ERROR: An RVM installation was not found.\n"
fi

> $TEST_LOG
> $VALGRIND_LOG
set -o errexit

function rvm_use {
    current_ruby=$1
    rvm use "${1}@nokogiri" --create
}

function clean {
    bundle exec rake clean clobber 2>&1 > /dev/null
}

function compile {
    echo "** compiling ..."
    bundle exec rake compile 2>&1 > /dev/null
}

# quick check that we have All The Rubies
for ruby in $RUBIES ; do
  rvm_use ${ruby}
done

for ruby in $RUBIES ; do
  rvm_use ${ruby}
  if ! [[ $(bundle -v) =~ "1.12." ]] ; then
    yes | gem uninstall --force bundler
    gem install bundler -v 1.12.5
    bundle -v
  fi
  bundle install --quiet --local || bundle install
  clean
done

for ruby in $RUBIES ; do
  rvm_use ${ruby}
  echo -e "**\n** testing nokogiri on ${ruby}\n**"
  clean
  compile
  echo "** running tests ..."
  bundle exec rake test 2>&1
  if [[ ! $ruby =~ "jruby" ]] ; then
    echo "** running tests again with libxml-ruby loaded ..."
    if ! gem list libxml-ruby | fgrep 2.8.0 ; then
      gem install libxml-ruby
    fi
    bundle exec rake test:libxml-ruby 2>&1
  fi
  clean
done | tee -a $TEST_LOG

for ruby in $RUBIES ; do
  if [[ ! $ruby =~ "jruby" ]] ; then
    rvm_use ${ruby}
    echo -e "**\n** nokogiri prerelease: ${ruby}\n**"
    clean
    compile
    echo "** running valgrind on tests ..."
    bundle exec rake test:valgrind 2>&1
    echo "** running valgrind again with libxml-ruby loaded ..."
    bundle exec rake test:valgrind:libxml-ruby 2>&1
    clean
  fi
done | tee -a $VALGRIND_LOG
