#!/bin/bash
# run script/test -h for help

# COLORS
OFF='\033[0m'
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'

set -e

function usage()
{
    echo -e "\t ================== script/test usage =================="
    echo -e "\t-h --help               : displays help message"
    echo -e "\t-d --disable-bootstrap  : disables bootstrap"
    echo -e "\t-l --local              : run for local testing"
    echo -e "\n\t Suggested flags for development: script/test -d -s"
}

while [ "$1" != "" ]; do
    PARAM=`echo $1 | awk -F= '{print $1}'`
    VALUE=`echo $1 | awk -F= '{print $2}'`
    case $PARAM in
      -h | --help)
        usage
        exit
        ;;
      -d | --disable-bootstrap)
        no_bootstrap=1
        ;;
      -l | --local)
        run_local=1
        ;;
      *)
      echo "ERROR: unknown parameter \"$PARAM\""
      usage
      exit 1
      ;;
    esac
    shift
done

# setup
export DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd .. && pwd )"
[ -z "$RBENV_VERSION" ] && export RBENV_VERSION=$(cat "$DIR/.ruby-version")

if [[ -z $no_bootstrap ]]; then
  # bootstrap
  echo -e "\n🥾 ${BLUE}Bootstrapping: $(date "+%H:%M:%S")${OFF}\n"
  echo "%%%FOLD {bootstrap}%%%"
  cd "$DIR"
  script/bootstrap
  echo "%%%END FOLD%%%"
else
  echo -e "\n⏩ ${BLUE}Skipping Bootstrap${OFF}"
fi

# Bootstraping mysql

echo "Bootstrapping MYSQL"
sleep 5
mysql -h ${DATABASE_HOST} -u root -proot vault_metadatas < ${DIR}/script/database/schema.sql
echo "Done bootstrapping MYSQL"

ping_vault() {
  HOST_AND_PORT=$(echo ${VAULT_ADDR} | awk -F/ '{print $3}')
  HOST=$(echo ${HOST_AND_PORT}  | awk -F\: '{print $1}')
  PORT=$(echo ${HOST_AND_PORT}  | awk -F\: '{print $2}')
  nc -zv $HOST $PORT 1>&2 && rc=$? || rc=$?
  return $rc
}

COUNTER=0
SUCCESS=0
while [ $COUNTER -lt 20 ]; do
  let COUNTER=COUNTER+1
  sleep 1
  if ping_vault; then
    SUCCESS=1
    break
  fi
  sleep 1
done

if [ "$SUCCESS" -eq 0 ]; then
  echo "" 1>&2
  echo "%%%HIGHLIGHT {danger}%%%" 1>&2
  echo "*** Error: Unable to connect to vault!" 1>&2
  echo "%%%END HIGHLIGHT%%%" 1>&2
  exit 255 1>&2
fi

# run tests
echo -e "\n🧪 ${BLUE}Running tests: $(date "+%H:%M:%S")${OFF}\n"
cd "$(dirname $0)/.."

if [[ -z $run_local ]]; then
  bundle exec rspec -f d spec/acceptance && rspec_exit=$? || rspec_exit=$?
  test_exit=$rspec_exit
else
  # running tests locally fails with 'Too many open files - getcwd (Errno::EMFILE)', so we break it up into multiple runs
  bundle exec rspec -f d spec/acceptance/lib/services && rspec_exit=$? || rspec_exit=$?
  test_exit=$rspec_exit
  for i in $(ls spec/acceptance/lib/*.rb); do
    bundle exec rspec -f d $i && rspec_exit=$? || rspec_exit=$?
    # save the first non-zero exit code, if any
    if [ $test_exit -eq 0 ]; then
      test_exit=$rspec_exit
    fi
  done
fi

echo ""
echo "---------------------------------------"
echo "📊 Summary Results"
echo "---------------------------------------"
echo ""

if [[ $test_exit == 0 ]]; then
  echo -e "✅ ${GREEN}rspec:    exitcode=${test_exit}${OFF}"
else
  echo -e "❌ ${RED}rspec:    exitcode=${test_exit}${OFF}"
fi

[ $test_exit -gt 0 ] && exit 1

exit 0
