#!/bin/bash
die() { echo "FATAL ERR: $*"; exit 1; }

# default to test env if RACK_ENV is undefined
if [ -z "$RACK_ENV" ]; then
  export RACK_ENV=test
fi

# The current git SHA
GITSHA=`git rev-parse HEAD`

# Check and use NVM if available
if [ -f "$NVM_DIR/nvm.sh" -a -f '.nvmrc' ]; then
  echo "Loading Node v`cat .nvmrc`"
  source $NVM_DIR/nvm.sh
  nvm use > /dev/null
else
  echo 'not using NVM'
fi

echo
echo "Using Node: `node --version`"
echo "Using NPM: `npm --version`"
echo "Using Ruby: `ruby --version`"
echo
echo

# Clean up previous build cruft
rm -rf /tmp/jest_preprocess_cache
rm -rf /tmp/npm-*     # Clean the npm install cache
rm -rf ./node_modules # This is brutal, but NPM won't pick up version changes between runs without it

bundle install --binstubs --path=.bundle

[ -f /data/modular_srm/shared/config/env ] && source /data/modular_srm/shared/config/env

bundle exec rake app:configure

if [ "$RACK_ENV" == "development" ] || [ "$RACK_ENV" == "test" ]; then
  npm install
  npm run-script build
else
  npm install --production
  npm run-script release
fi

if [ ! -z "$JOB_NAME" ]; then
  cp config/database.yml.hudson config/database.yml
fi

bundle exec rake db:drop db:create
bundle exec rake db:schema:load
bundle exec rspec spec

npm test
