#!/usr/bin/env bash
#
# Summary: List all Python virtualenvs found in `$PYENV_ROOT/versions/*'.
# Usage: pyenv virtualenvs [--bare] [--skip-aliases]
#
# List all virtualenvs found in `$PYENV_ROOT/versions/*' and its `$PYENV_ROOT/versions/envs/*'.

set -e
[ -n "$PYENV_DEBUG" ] && set -x
if [ -L "${BASH_SOURCE}" ]; then
    READLINK=$(type -p greadlink readlink | head -1)
    if [ -z "$READLINK" ]; then
        echo "pyenv: cannot find readlink - are you missing GNU coreutils?" >&2
        exit 1
    fi
    resolve_link() {
        $READLINK -f "$1"
    }
    script_path=$(resolve_link ${BASH_SOURCE})
else
    script_path=${BASH_SOURCE}
fi

. ${script_path%/*}/../libexec/pyenv-virtualenv-realpath

if [ -z "$PYENV_ROOT" ]; then
  PYENV_ROOT="${HOME}/.pyenv"
fi

unset bare
unset skip_aliases
# Provide pyenv completions
for arg; do
  case "$arg" in
  --complete )
    echo --bare
    echo --skip-aliases
    exit ;;
  --bare ) bare=1 ;;
  --skip-aliases ) skip_aliases=1 ;;
  * )
    pyenv-help --usage virtualenvs >&2
    exit 1
    ;;
  esac
done

versions_dir="${PYENV_ROOT}/versions"

if [ -d "$versions_dir" ]; then
  versions_dir="$(realpath "$versions_dir")"
fi

if [ -n "$bare" ]; then
  hit_prefix=""
  miss_prefix=""
  current_versions=()
  unset print_origin
  include_system=""
else
  hit_prefix="* "
  miss_prefix="  "
  OLDIFS="$IFS"
  IFS=: current_versions=($(pyenv-version-name || true))
  IFS="$OLDIFS"
  print_origin="1"
  include_system=""
fi

num_versions=0

exists() {
  local car="$1"
  local cdar
  shift
  for cdar in "$@"; do
    if [ "${car}" == "${cdar}" ]; then
      return 0
    fi
  done
  return 1
}

print_version() {
  if exists "$1" "${current_versions[@]}"; then
    echo "${hit_prefix}${1}${print_origin+$2}"
  else
    echo "${miss_prefix}${1}${print_origin+$2}"
  fi
  num_versions=$((num_versions + 1))
}

shopt -s dotglob
shopt -s nullglob
for path in "$versions_dir"/*; do
  if [ -d "$path" ]; then
    if [ -n "$skip_aliases" ] && [ -L "$path" ]; then
      target="$(realpath "$path")"
      [ "${target%/*/envs/*}" != "$versions_dir" ] || continue
    fi
    virtualenv_prefix="$(pyenv-virtualenv-prefix "${path##*/}" 2>/dev/null || true)"
    if [ -d "${virtualenv_prefix}" ]; then
      print_version "${path##*/}" " (created from ${virtualenv_prefix})"
    fi
    for venv_path in "${path}/envs/"*; do
      venv="${path##*/}/envs/${venv_path##*/}"
      virtualenv_prefix="$(pyenv-virtualenv-prefix "${venv}" 2>/dev/null || true)"
      if [ -d "${virtualenv_prefix}" ]; then
        print_version "${venv}" " (created from ${virtualenv_prefix})"
      fi
    done
  fi
done
shopt -u dotglob
shopt -u nullglob

if [ "$num_versions" -eq 0 ] && [ -n "$include_system" ]; then
  echo "Warning: no Python virtualenv detected on the system" >&2
  exit 1
fi
