#!/usr/bin/env bash
#
# Summary: Uninstall a specific Go version
#
# Usage: goenv uninstall [-f|--force] <version>
#
#    -f  Attempt to remove the specified version without prompting
#        for confirmation. Still displays error message if version does not exist.
#
# See `goenv versions` for a complete list of installed versions.
#
set -e
[ -n "$GOENV_DEBUG" ] && set -x

# Provide goenv completions
if [ "$1" = "--complete" ]; then
  echo --force
  exec goenv versions --bare
fi

usage() {
  goenv-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

if [ ! "$#" -eq 1 ]; then
  usage 1 >&2
fi

DEFINITION="$1"
case "$DEFINITION" in
"" | -* )
  usage 1 >&2
  ;;
esac

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"
}

OLDIFS="$IFS"
IFS=$'\n' scripts=(`goenv-hooks uninstall`)
IFS="$OLDIFS"
for script in "${scripts[@]}"; do
  source "$script";
done

VERSION_NAME="${DEFINITION##*/}"
# NOTE: Try to capture semantic versions such as `1.11` which don't have a patch version.
# A patch version of 0 will be added, e.g they'll be changed to `1.11.0`.
if grep -q -E "^[0-9]+\.[0-9]+(\s*)$" <<< ${VERSION_NAME}; then
  echo "Adding patch version 0 to ${VERSION_NAME}"
  VERSION_NAME="${VERSION_NAME}.0"
fi

PREFIX="${GOENV_ROOT}/versions/${VERSION_NAME}"

if [ ! -d "$PREFIX" ]; then
  echo "goenv: version '$VERSION_NAME' not installed" >&2
  exit 1
fi

if [ -z "$FORCE" ]; then
  read -p "goenv: remove $PREFIX? "
  case "$REPLY" in
  y* | Y* ) ;;
  * ) exit 1 ;;
  esac
fi

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

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

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