#!/usr/bin/env bash

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 #
#####################

uninstall_single_version() {
  local version_requested="${1}";

  log 'debug' "Version Requested: ${version_requested}";

  if [[ "${version_requested}" =~ ^min-required$ ]]; then
    log 'error' 'min-required is an unsupported option for uninstall';
  fi;

  if [[ "${version_requested}" == latest-allowed ]]; then
    log 'error' 'latest-allowed is an unsupported option for uninstall';
  fi;

  local version regex;
  if [[ "${version_requested}" =~ ^latest\:.*$ ]]; then
    version="${version_requested%%\:*}";
    regex="${version_requested##*\:}";
  elif [[ "${version_requested}" =~ ^latest$ ]]; then
    version="${version_requested}";
    regex="";
  else
    version="${version_requested}";
    regex="^${version_requested}$";
  fi;

  [ -z "${version:-""}" ] && log 'error' "Version not specified.";

  log 'debug' "Processing uninstall for version ${version}, using regex ${regex}";

  version="$(tfenv-list | sed -E 's/^(\*| )? //g; s/ \([^)]+\)//g' | grep -e "${regex}" | head -n 1)";
  [ -n "${version}" ] || log 'error' "No versions matching '${regex}' found in local";

  local dst_path="${TFENV_CONFIG_DIR}/versions/${version}";
  if [ -f "${dst_path}/terraform" ]; then
    log 'info' "Uninstall Terraform v${version}";
    rm -r "${dst_path}";
    log 'info' "Terraform v${version} is successfully uninstalled";
  else
    log 'error' "Terraform v${version} is not installed";
  fi;
};

# Collect versions to uninstall
declare -a versions_to_uninstall=();

if [ "${#}" -eq 0 ] && [ -z "${TFENV_TERRAFORM_VERSION:-""}" ]; then
  # No args: read from version file
  version_file="$(tfenv-version-file)";
  log 'debug' "Version File: ${version_file}";
  if [ "${version_file}" != "${TFENV_CONFIG_DIR}/version" ]; then
    log 'debug' "Version File (${version_file}) is not the default \${TFENV_CONFIG_DIR}/version (${TFENV_CONFIG_DIR}/version)";
    versions_to_uninstall+=("$(read_version_file "${version_file}")") \
      || log 'error' "Failed to open ${version_file}";
  elif [ -f "${version_file}" ]; then
    log 'debug' "Version File is the default \${TFENV_CONFIG_DIR}/version (${TFENV_CONFIG_DIR}/version)";
    versions_to_uninstall+=("$(read_version_file "${version_file}")") \
      || log 'error' "Failed to open ${version_file}";
  else
    log 'error' 'No version requested on the command line or in the version file search path.';
  fi;
elif [ "${#}" -eq 0 ] && [ -n "${TFENV_TERRAFORM_VERSION:-""}" ]; then
  versions_to_uninstall+=("${TFENV_TERRAFORM_VERSION}");
  log 'debug' "TFENV_TERRAFORM_VERSION is set: ${TFENV_TERRAFORM_VERSION}";
else
  versions_to_uninstall=("$@");
fi;

[ "${#versions_to_uninstall[@]}" -gt 0 ] \
  || log 'error' 'No versions specified for uninstall.';

declare -i fail_count=0;
for ver in "${versions_to_uninstall[@]}"; do
  # Run in subshell so log 'error' (which calls exit 1) does not kill the loop
  (uninstall_single_version "${ver}") || ((fail_count++));
done;

# If no versions remain, remove the versions directory
if [ -d "${TFENV_CONFIG_DIR}/versions" ]; then
  rmdir "${TFENV_CONFIG_DIR}/versions" 2>/dev/null || true;
fi;

[ "${fail_count}" -eq 0 ] || exit 1;
