#!/usr/bin/env bash

try() {
  output=$(mktemp -d)
  "$@" > "$output/stdout" 2> "$output/stderr"
  EXIT_CODE=$?
  STDOUT=$(<"$output/stdout")
  STDERR=$(<"$output/stderr")
  export EXIT_CODE STDOUT STDERR
  rm -rf "$output"
}

setUp() {
  export TMPDIR="$PWD/.generated"
  export-repo-root
  move-to-working-directory
}

tearDown() {
  [ "${_shunit_test_:=}" = '' ] && return 0

  clean-up-working-directory

  if [ "${__shunit_testSuccess:?}" != 0 ]; then
    output-outputs
  fi
}

export-repo-root() {
  export REPO_ROOT="$PWD"
  while ! [[ -d $REPO_ROOT/.git ]]; do
    export REPO_ROOT=$(dirname $REPO_ROOT)
  done
}

move-to-working-directory() {
  original_dir="$PWD"
  working_dir=$(mktemp -d)
  cd $working_dir
}

clean-up-working-directory() {
  cd $original_dir
  rm -rf $working_dir
}

output-outputs() {
  (
  bold '*******Test failed********'
  echo "$(bold EXIT_CODE =) $EXIT_CODE"
  bold STDOUT    :
  echo "$STDOUT"
  bold STDERR    :
  echo "$STDERR"
  ) >&2
}

bold() {
  echo -ne "\033[1m"
  echo -ne "$@"
  echo -e "\033[0m"
}

SHUNIT_PATH=./.generated/shunit2-2.1.8/shunit2
if [ ! -f $SHUNIT_PATH ]; then (
  mkdir -p .generated
  cd .generated
  curl -LO https://github.com/kward/shunit2/archive/v2.1.8.zip
  unzip v2.1.8.zip
)
fi


source $SHUNIT_PATH