#!/bin/bash

set -e -x

function is_jruby() {
  if ruby -e 'exit RUBY_PLATFORM == "java"'; then
    return 0
  else
    return 1
  fi
}

# idea taken from: http://blog.headius.com/2010/03/jruby-startup-time-tips.html
export JRUBY_OPTS='-X-C' # disable JIT since these processes are so short lived

# force jRuby to use client mode JVM or a compilation mode thats as close as possible,
# idea taken from https://github.com/jruby/jruby/wiki/Improving-startup-time
export JAVA_OPTS='-client -XX:+TieredCompilation -XX:TieredStopAtLevel=1'

echo "Running all..."
script/rspec_with_simplecov spec -b --format progress --profile

echo
echo "--------------------------------------------------------------------"
echo

if is_jruby; then
  echo "Skipping one-by-one spec runs due to expensive JVM load time"
else
  for file in `find spec -iname '*_spec.rb'`; do
    bin/rspec $file -b --format progress
  done
fi

# Prepare RUBYOPT for scenarios that are shelling out to ruby,
# and PATH for those that are using `rspec` or `rake`.
# RUBYOPT="-I${PWD}/bundle -rbundler/setup" \
#   PATH="${PWD}/bin:$PATH" \
#   bin/cucumber

# For now, use this instead, due to a bug in bundler:
# https://github.com/carlhuda/bundler/issues/2382
bundle exec bin/cucumber --strict

script/prevent_runtime_method_cache_busters

# Test against other RSpec gems.

# Delete the directory for idempotency when running locally
export TMPDIR="/tmp"
rm -rf $TMPDIR/rspec-ci
mkdir $TMPDIR/rspec-ci

# Get the branch to test against
MAINTENENCE_BRANCH=`cat maintenence-branch`

cp -r "./" "$TMPDIR/rspec-ci/rspec-core"

#Change to the CI directory
cd $TMPDIR/rspec-ci

# The steps to test the gems are the same, this function does them.
function test_gem {
    git clone git://github.com/rspec/rspec-$1
    cd rspec-$1
    pwd
    git fetch origin
    git checkout $MAINTENENCE_BRANCH
    git branch
    bundle_flags=`cat .travis.yml  | grep bundler_args | tr -d '"' | grep -o " .*"`

    bundle install $bundle_flags
    bundle exec rspec -b
    cd ../
    rm -rf rspec-$1
}

# Test rspec-mocks and rspec-expectations.
test_gem "mocks"
test_gem "expectations"
