#!/usr/bin/env bash
#
# Summary: Display the full path to an executable
#
# Usage: rbenv which <command>
#
# Displays the full path to the executable that rbenv will invoke when
# you run the given command.

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

# Provide rbenv completions
if [ "$1" = "--complete" ]; then
  exec rbenv shims --short
fi

expand_path() {
  if [ ! -d "$1" ]; then
    return 1
  fi

  local cwd="$(pwd)"
  cd "$1"
  pwd
  cd "$cwd"
}

remove_from_path() {
  local path_to_remove="$(expand_path "$1")"
  local result=""

  if [ -z "$path_to_remove" ]; then
    echo "${PATH}"
    return
  fi

  local paths
  IFS=: paths=($PATH)

  for path in "${paths[@]}"; do
    path="$(expand_path "$path" || true)"
    if [ -n "$path" ] && [ "$path" != "$path_to_remove" ]; then
      result="${result}${path}:"
    fi
  done

  echo "${result%:}"
}

RBENV_VERSION="$(rbenv-version-name)"
RBENV_COMMAND="$1"

if [ -z "$RBENV_COMMAND" ]; then
  rbenv-help --usage which >&2
  exit 1
fi

if [ "$RBENV_VERSION" = "system" ]; then
  PATH="$(remove_from_path "${RBENV_ROOT}/shims")"
  RBENV_COMMAND_PATH="$(command -v "$RBENV_COMMAND" || true)"
else
  RBENV_COMMAND_PATH="${RBENV_ROOT}/versions/${RBENV_VERSION}/bin/${RBENV_COMMAND}"
fi

for script in $(rbenv-hooks which); do
  source "$script"
done

if [ -x "$RBENV_COMMAND_PATH" ]; then
  echo "$RBENV_COMMAND_PATH"
else
  echo "rbenv: $RBENV_COMMAND: command not found" >&2

  versions="$(rbenv-whence "$RBENV_COMMAND" || true)"
  if [ -n "$versions" ]; then
    { echo
      echo "The \`$1' command exists in these Ruby versions:"
      echo "$versions" | sed 's/^/  /g'
      echo
    } >&2
  fi

  exit 127
fi
