#!/usr/bin/env bash
# Usage: tfenv version-file
# Summary: Detect the file that sets the current tfenv version

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 libexec and bin are in $PATH
for dir in libexec bin; do
  case ":${PATH}:" in
    *:${TFENV_ROOT}/${dir}:*) log 'debug' "\$PATH already contains '${TFENV_ROOT}/${dir}', not adding it again";;
    *) 
      log 'debug' "\$PATH does not contain '${TFENV_ROOT}/${dir}', prepending and exporting it now";
      export PATH="${TFENV_ROOT}/${dir}:${PATH}";
      ;;
  esac;
done;

#####################
# Begin Script Body #
#####################

find_local_version_file() {
  log 'debug' "Looking for a version file in ${1}";
  local root="${1}";
  while ! [[ "${root}" =~ ^//[^/]*$ ]]; do
    if [ -e "${root}/.terraform-version" ]; then
      log 'debug' "Found at ${root}/.terraform-version";
      echo "${root}/.terraform-version";
      return 0;
    else
      log 'debug' "Not found at ${root}/.terraform-version";
    fi;
    [ -n "${root}" ] || break;
    root="${root%/*}";
  done;
  log 'debug' "No version file found in ${1}";
  return 1;
}

if ! find_local_version_file "${TFENV_DIR:-${PWD}}"; then
  if ! find_local_version_file "${HOME:-/}"; then
    log 'debug' "No version file found in search paths. Defaulting to TFENV_CONFIG_DIR: ${TFENV_CONFIG_DIR}/version";
    echo "${TFENV_CONFIG_DIR}/version";
  fi;
fi;
