#!/usr/bin/env bash
# Summary: List all available nodenv commands
# Usage: nodenv commands [--sh|--no-sh]
#
# List names of all nodenv commands, including 3rd-party ones found in the
# PATH or in nodenv plugins. With `--sh`, list only shell commands.
#
# This functionality is mainly meant for scripting. To see usage help for
# nodenv, run `nodenv help`.

set -e
[ -n "$NODENV_DEBUG" ] && set -x

# Provide nodenv completions
if [ "$1" = "--complete" ]; then
  echo --sh
  echo --no-sh
  exit
fi

exclude_shell=
command_prefix="nodenv-"

if [ "$1" = "--sh" ]; then
  command_prefix="nodenv-sh-"
  shift
elif [ "$1" = "--no-sh" ]; then
  exclude_shell=1
  shift
fi

shopt -s nullglob

{
  PATH_remain="$PATH"
  # traverse PATH to find "nodenv-" prefixed commands
  while true; do
    path="${PATH_remain%%:*}"
    if [ -n "$path" ]; then
      for nodenv_command in "${path}/${command_prefix}"*; do
        nodenv_command="${nodenv_command##*nodenv-}"
        if [[ -z $exclude_shell || $nodenv_command != sh-* ]]; then
          echo "${nodenv_command##sh-}"
        fi
      done
    fi
    [[ $PATH_remain == *:* ]] || break
    PATH_remain="${PATH_remain#*:}"
  done
} | sort | uniq
