#!/usr/bin/env bash

# Common test setup header
# Source this file at the beginning of test scripts to set up the test environment

set -uo pipefail;

####################################
# Ensure we can execute standalone #
####################################

function early_death() {
  echo "[FATAL] ${0}: ${1}" >&2;
  exit 1;
};

if [ -z "${TFENV_ROOT:-""}" ]; then
  # http://stackoverflow.com/questions/1055671/how-can-i-get-the-behavior-of-gnus-readlink-f-on-a-mac
  readlink_f() {
    local target_file="${1}";
    local file_name;

    while [ "${target_file}" != "" ]; do
      cd "$(dirname ${target_file})" || early_death "Failed to 'cd \$(dirname ${target_file})' while trying to determine TFENV_ROOT";
      file_name="$(basename "${target_file}")" || early_death "Failed to 'basename \"${target_file}\"' while trying to determine TFENV_ROOT";
      target_file="$(readlink "${file_name}")";
    done;

    echo "$(pwd -P)/${file_name}";
  };

  TFENV_ROOT="$(cd "$(dirname "$(readlink_f "${0}")")/.." && pwd)";
  [ -n "${TFENV_ROOT}" ] || early_death "Failed to 'cd \"\$(dirname \"\$(readlink_f \"${0}\")\")/..\" && pwd' while trying to determine TFENV_ROOT";
else
  TFENV_ROOT="${TFENV_ROOT%/}";
fi;
export TFENV_ROOT;

if [ -n "${TFENV_HELPERS:-""}" ]; then
  log 'debug' 'TFENV_HELPERS is set, not sourcing helpers again';
else
  [ "${TFENV_DEBUG:-0}" -gt 0 ] && echo "[DEBUG] Sourcing helpers from ${TFENV_ROOT}/lib/helpers.sh";
  if source "${TFENV_ROOT}/lib/helpers.sh"; then
    log 'debug' 'Helpers sourced successfully';
  else
    early_death "Failed to source helpers from ${TFENV_ROOT}/lib/helpers.sh";
  fi;
fi;

# Ensure local tfenv binaries take precedence
export PATH="${TFENV_ROOT}/bin:${PATH}";

##############################
# Environment var isolation  #
##############################

# Use an isolated TFENV_CONFIG_DIR for tests so we never pollute the real install.
# Individual tests can override this if they need to test TFENV_CONFIG_DIR itself.
if [ -z "${TFENV_TEST_NO_ISOLATE:-""}" ]; then
  TFENV_TEST_DIR="$(mktemp -d 2>/dev/null || mktemp -d -t 'tfenv_test')";
  export TFENV_CONFIG_DIR="${TFENV_TEST_DIR}";
  # Clean up the isolated directory on exit
  trap 'rm -rf "${TFENV_TEST_DIR}"' EXIT;
fi;

####################
# Test helpers     #
####################

# Standard test suite finaliser. Call at the end of every test file.
# Uses the 'errors' array populated by error_and_proceed.
# Arguments: $1 = suite name (e.g. 'install_and_use')
function finish_tests() {
  local suite="${1}";
  if [ "${#errors[@]}" -gt 0 ]; then
    log 'warn' "===== The following ${suite} tests failed =====";
    for error in "${errors[@]}"; do
      log 'warn' "\t${error}";
    done;
    log 'error' "${suite} test failure(s)";
    exit 1;
  else
    log 'info' "All ${suite} tests passed.";
  fi;
};
export -f finish_tests;
