#!/bin/bash
#
# Summary: Uninstall a specific Node version
#
# Usage: nodenv uninstall [-f|--force] <version>...
#
#    -f  Attempt to remove the specified version without prompting
#        for confirmation. If the version does not exist, do not
#        display an error message.
#
# See `nodenv versions` for a complete list of installed versions.
#
set -e

# Provide nodenv completions
if [ "$1" = "--complete" ]; then
  exec comm -23 \
  <({ echo --force; nodenv versions --bare;} | sort) \
  <(printf "%s\n" "${@:1}" | sort)
fi

usage() {
  nodenv-help uninstall 2>/dev/null
  [ -z "$1" ] || exit "$1"
}

if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  usage 0
fi

unset FORCE
if [ "$1" = "-f" ] || [ "$1" = "--force" ]; then
  FORCE=true
  shift
fi

[ "$#" -gt 0 ] || usage 1 >&2

DEFINITIONS=("$@")

for DEFINITION in "${DEFINITIONS[@]}"; do
  case "$DEFINITION" in
  "" | -* ) usage 1 >&2 ;;
  esac
done

declare -a before_hooks after_hooks

before_uninstall() {
  local hook="$1"
  before_hooks["${#before_hooks[@]}"]="$hook"
}

after_uninstall() {
  local hook="$1"
  after_hooks["${#after_hooks[@]}"]="$hook"
}

while IFS=$'\n' read -r script; do
  scripts+=("$script")
done < <(nodenv-hooks uninstall)
# shellcheck disable=SC1090
for script in "${scripts[@]}"; do source "$script"; done

STATUS=0

for DEFINITION in "${DEFINITIONS[@]}"; do

  VERSION_NAME="${DEFINITION##*/}"
  PREFIX="${NODENV_ROOT}/versions/${VERSION_NAME}"

  if [ -z "$FORCE" ]; then
    if [ ! -d "$PREFIX" ]; then
      echo "nodenv: version \`$VERSION_NAME' not installed" >&2
      STATUS=1
      continue
    fi

    read -rp "nodenv: remove $PREFIX? [yN] "
    case "$REPLY" in
    y* | Y* ) ;;
    * ) STATUS=1; continue ;;
    esac
  fi

  for hook in "${before_hooks[@]}"; do eval "$hook"; done

  if [ -d "$PREFIX" ]; then
    rm -rf "$PREFIX"
    nodenv-rehash
  fi

  for hook in "${after_hooks[@]}"; do eval "$hook"; done

done

exit $STATUS
