#!/bin/bash
#

if [ "$1" == "-h" ]; then
  echo "Purpose:"
  echo ""
  echo " Runs 'go test' locally with race detector turned on, any additional flags will be"
  echo " forwarded to 'go test'."
  echo ""
  echo "Environment Variables:"
  echo ""
  echo " RUNNING_IN_DOCKER=(1) [default: unset]"
  echo "   Indicates that this is running in a docker image, main difference is that test"
  echo "   results are output to files."
  echo ""
  echo " RUN_ALL=(1) [default: unset]"
  echo "   Run all tests in this project. If unset only tests in './internal/...' will run."
  exit 0
fi

set -ex

pushd "$(dirname "${BASH_SOURCE[0]}")/.." || exit 1

cmd="go test"
testpath="./test/..."
if [ "$RUN_ALL" == '1' ]; then
  testpath="./..."
fi

if [ "$RUNNING_IN_DOCKER" != "1" ]; then
  # local test mode

  # run github.com/rakyll/gotest if available
  if hash gotest 2>/dev/null; then
    cmd='gotest'
  fi

  $cmd -race "$@" "$testpath"

  popd || exit 1
  exit 0
fi

# docker test mode
TESTOUTPUT_DIR=/tmp/testoutput

EXIT_CODE_FILE=${TESTOUTPUT_DIR}/test.sh.exit_code
STDALL_FILE=${TESTOUTPUT_DIR}/report-stdall.txt
STDERR_FILE=${TESTOUTPUT_DIR}/report-stderr.txt
STDOUT_FILE=${TESTOUTPUT_DIR}/report-stdout.txt
XML_REPORT=${TESTOUTPUT_DIR}/report.xml
HTML_REPORT=${TESTOUTPUT_DIR}/report.html

do_exit() {
  local exit_code=${1}

  echo "$exit_code" > ${EXIT_CODE_FILE}
  exit "$exit_code"
}

pwd

go test -race -v -count=1 "$testpath" -p 1 2> >(tee ${STDERR_FILE}) | tee ${STDOUT_FILE}

exit_code=${PIPESTATUS[0]}

go-test-html ${STDOUT_FILE} ${STDERR_FILE} ${HTML_REPORT}

if [ $? -ne 0 ]; then
  exit_code=$?
fi

go2xunit -fail -input ${STDOUT_FILE} -output ${XML_REPORT}

if [ $? -ne 0 ]; then
  exit_code=$?
fi

popd || do_exit 1
do_exit ${exit_code}
