#!/usr/bin/env bash
# Usage: nodenv doctor
# Summary: Detects common problems in nodenv installation

set -e
[ -n "$NODENV_DEBUG" ] && { export PS4='+ [${BASH_SOURCE##*/}:${LINENO}] '; set -x; }

count-lines() {
  printf "%d" "$(wc -l)"
}

command-list() {
  # shellcheck disable=SC2230
  which -a "$1"
}

indent() {
  sed 's/^/  /'
}

# for ubuntu /bin is a symlink to /usr/bin
# which -a doesn't know the binaries are the same
fix-usr-bin() {
  sed 's:^/usr/bin/:/bin/:'
}

printc() {
  local color_name="color_$1"
  local msg="$2"
  printf "%s%s%s" "${!color_name}" "$msg" "$color_reset"
}

if [ -t 1 ]; then
  # shellcheck disable=SC2034
  color_red=$'\e[31m'
  # shellcheck disable=SC2034
  color_green=$'\e[32m'
  # shellcheck disable=SC2034
  color_yellow=$'\e[1;33m'
  # shellcheck disable=SC2034
  color_bright=$'\e[1;37m'
  color_reset=$'\e[0m'
else
  # shellcheck disable=SC2034
  color_red=""
  # shellcheck disable=SC2034
  color_green=""
  # shellcheck disable=SC2034
  color_yellow=""
  # shellcheck disable=SC2034
  color_bright=""
  # shellcheck disable=SC2034
  color_reset=""
fi

warnings=0

echo -n "Checking for \`nodenv' in PATH: "
num_locations="$(command-list nodenv | fix-usr-bin | uniq | count-lines)"
if [ "$num_locations" -eq 0 ]; then
  printc red "not found"
  echo
  { if [ -x "$HOME/.nodenv/bin/nodenv" ] || [ -x "${NODENV_ROOT:-}/bin/nodenv" ]; then
      [ -x "$HOME/.nodenv/bin/nodenv" ] &&
        echo "You seem to have nodenv installed in \`$HOME/.nodenv/bin',"
      [ -x "${NODENV_ROOT:-}/bin/nodenv" ] &&
        echo "You seem to have nodenv installed in \`$NODENV_ROOT/bin',"
      echo "but that directory is not present in PATH."
      echo "Please add it to PATH by configuring your shell initialization files."
    else
      echo "Please refer to https://github.com/nodenv/nodenv#installation"
    fi
  } | indent

  if [ -n "$(find "${NODENV_ROOT:-~/.nodenv}/bin/nodenv" -mmin 1 2>/dev/null)" ]; then
    printc bright "Recent installation detected.\n"
    { echo "Complete the installation by configuring your PATH as above,"
      echo "and re-run nodenv-doctor in a fresh shell."
    } | indent
    exit 0
  fi

  exit 1
elif [ "$num_locations" -eq 1 ]; then
  printc green "$(command -v nodenv)"
  echo
else
  printc yellow "multiple"
  echo
  { echo "You seem to have multiple nodenv installs in the following locations."
    echo "Please pick just one installation and remove the others."
    echo
    command-list nodenv
  } | indent
  echo
  : $((warnings++))
fi

NODENV_ROOT="${NODENV_ROOT:-$(nodenv root)}"

echo -n "Checking for nodenv shims in PATH: "
shims_dir="${NODENV_ROOT}/shims"
found=""
precedence_problem=""
IFS=: read -r -a path <<<"$PATH" || true
for dir in "${path[@]}"; do
  if [ "$dir" = "$shims_dir" ]; then
    found=true
  elif [ -x "$dir"/node ] && [ -z "$found" ]; then
    precedence_problem="$dir"
  fi
done
if [ -n "$found" ]; then
  if [ -n "$precedence_problem" ]; then
    printc yellow "found at wrong position"
    echo
    { echo "The directory \`$shims_dir' is present in PATH, but is listed too late."
      echo "The Node version found in \`$precedence_problem' will have precedence. Please reorder your PATH."
    } | indent
    echo
    : $((warnings++))
  else
    printc green "OK"
    echo
  fi
else
  printc red "not found"
  echo
  { echo "The directory \`$shims_dir' must be present in PATH for nodenv to work."
    echo "Please run \`nodenv init' and follow the instructions."
  } | indent
  echo
  : $((warnings++))
fi

echo -n "Checking \`nodenv install' support: "
nodenv_installs="$({ ls "$NODENV_ROOT"/plugins/*/bin/nodenv-install 2>/dev/null || true
                    command-list nodenv-install 2>/dev/null || true
                  } | uniq)"
num_installs="$(count-lines <<<"$nodenv_installs")"
if [ -z "$nodenv_installs" ]; then
  printc red "not found"
  echo
  { echo "Unless you plan to add Node versions manually, you should install node-build."
    echo "Please refer to https://github.com/nodenv/node-build#installation"
  }
  echo
  : $((warnings++))
elif [ "$num_installs" -eq 1 ]; then
  printc green "$nodenv_installs"
  if [[ $nodenv_installs == "$NODENV_ROOT"/plugins/* ]]; then
    nodenv_install_cmd="${nodenv_installs##*/}"
    nodenv_install_version="$(nodenv "${nodenv_install_cmd#nodenv-}" --version || true)"
  else
    nodenv_install_version="$("$nodenv_installs" --version || true)"
  fi
  printf " (%s)\n" "$nodenv_install_version"
else
  printc yellow "multiple"
  echo
  { echo "You seem to have multiple \`nodenv-install' in the following locations."
    echo "Please pick just one installation and remove the others."
    echo
    echo "$nodenv_installs"
  } | indent
  echo
  : $((warnings++))
fi

echo -n "Counting installed Node versions: "
num_nodes="$(nodenv versions --bare | count-lines)"
if [ "$num_nodes" -eq 0 ]; then
  printc yellow "none"
  echo
  echo "There aren't any Node versions installed under \`$NODENV_ROOT/versions'." | indent
  [ "$num_installs" -eq 0 ] || {
    latest_version="$(nodenv install -l 2>/dev/null | grep -vFe - | tail -1)"
    [ -n "$latest_version" ] || latest_version="<version>"
    echo -n "You can install Node versions like so: "
    printc bright "nodenv install $latest_version"
    echo
  } | indent
else
  printc green "$num_nodes versions"
  echo
fi

echo -n "Auditing installed plugins: "
hooks_list="$(nodenv hooks exec || true)"
IFS=$'\n' read -r -d '' -a hooks <<<"$hooks_list" || true
plugin_broken=0
for hook in "${hooks[@]}"; do
  plugin_name=
  message=

  if [ -n "$plugin_name" ]; then
    if [ "$((plugin_broken++))" -eq 0 ]; then
      printc yellow "warning"
      echo
    fi
    { printc bright "$plugin_name"
      echo " $message"
      echo "  (found in \`${hook}')"
    } | indent
    : $((warnings++))
  fi
done
if [ "$plugin_broken" -eq 0 ]; then
  printc green "OK"
  echo
fi

if [ "$warnings" -gt 0 ]; then
  exit 1
fi
