#!/usr/bin/env bash

set -uo pipefail;

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

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

if [ -z "${TOFUENV_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 TOFUENV_ROOT";
      file_name="$(basename "${target_file}")" || early_death "Failed to 'basename \"${target_file}\"' while trying to determine TOFUENV_ROOT";
      target_file="$(readlink "${file_name}")";
    done;

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

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

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

# Ensure libexec and bin are in $PATH
for dir in libexec bin; do
  case ":${PATH}:" in
    *:${TOFUENV_ROOT}/${dir}:*) log 'debug' "\$PATH already contains '${TOFUENV_ROOT}/${dir}', not adding it again";;
    *)
      log 'debug' "\$PATH does not contain '${TOFUENV_ROOT}/${dir}', prepending and exporting it now";
      export PATH="${TOFUENV_ROOT}/${dir}:${PATH}";
      ;;
  esac;
done;

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

[ "${#}" -gt 1 ] && log 'error' 'usage: tofuenv uninstall [<version>]';

declare version_requested version regex;
declare arg="${1:-""}";

if [ -z "${arg:-""}" ] && [ -z "${TOFUENV_TOFU_VERSION:-""}" ]; then
  version_file="$(tofuenv-version-file)";
  log 'debug' "Version File: ${version_file}";
  if [ "${version_file}" != "${TOFUENV_CONFIG_DIR}/version" ]; then
    log 'debug' "Version File (${version_file}) is not the default \${TOFUENV_CONFIG_DIR}/version (${TOFUENV_CONFIG_DIR}/version)";
    version_requested="$(cat "${version_file}")" \
      || log 'error' "Failed to open ${version_file}";
  elif [ -f "${version_file}" ]; then
    log 'debug' "Version File is the default \${TOFUENV_CONFIG_DIR}/version (${TOFUENV_CONFIG_DIR}/version)";
    version_requested="$(cat "${version_file}")" \
      || log 'error' "Failed to open ${version_file}";
  else
    log 'debug' "Version File is the default \${TOFUENV_CONFIG_DIR}/version (${TOFUENV_CONFIG_DIR}/version) but it doesn't exist";
    log 'info' 'No version requested on the command line or in the version file search path. Installing "latest"';
    version_requested='latest';
  fi;
elif [ -n "${TOFUENV_TOFU_VERSION:-""}" ]; then
  version_requested="${TOFUENV_TOFU_VERSION}";
  log 'debug' "TOFUENV_TOFU_VERSION is set: ${TOFUENV_TOFU_VERSION}";
else
  version_requested="${arg}";
fi;

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;

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 on the command line or on version file search path.";

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

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

dst_path="${TOFUENV_CONFIG_DIR}/versions/${version}";
if [ -f "${dst_path}/tofu" ]; then
  log 'info' "Uninstall OpenTofu v${version}";
  rm -r "${dst_path}";

  # If no versions remain, remove the versions directory
  rmdir "${TOFUENV_CONFIG_DIR}/versions" 2>/dev/null;

  log 'info' "OpenTofu v${version} is successfully uninstalled";
fi;
