# if virtualenv is created with `--system-site-packages`,
# looks up executables for source version as well if none is
# installed in the virtualenv.
# https://github.com/yyuu/pyenv-virtualenv/issues/62

if [ ! -x "${PYENV_COMMAND_PATH}" ]; then
  OLDIFS="${IFS}"
  IFS=:
  version="$(pyenv-version-name)"
  IFS="${OLDIFS}"
  if [ -f "${PYENV_ROOT}/versions/${version}/bin/activate" ]; then
    unset include_system_site_packages
    if [ -f "${PYENV_ROOT}/versions/${version}/bin/conda" ]; then
      : # do nothing for conda's environments
    else
      if [ -f "${PYENV_ROOT}/versions/${version}/pyvenv.cfg" ]; then
        # venv
        virtualenv_binpath="$(cut -b 1-1024 "${PYENV_ROOT}/versions/${version}/pyvenv.cfg" | sed -n '/^ *home *= */s///p' || true)"
        virtualenv_prefix="${virtualenv_binpath%/bin}"
        if grep -q -i "include-system-site-packages *= *true" "${PYENV_ROOT}/versions/${version}/pyvenv.cfg" 1>/dev/null 2>&1; then
          include_system_site_packages=1
        fi
      else
        # virtualenv
        if [ -d "${PYENV_ROOT}/versions/${version}/Lib" ]; then
          # jython
          virtualenv_libpath="${PYENV_ROOT}/versions/${version}/Lib"
        else
          if [ -d "${PYENV_ROOT}/versions/${version}/lib-python" ]; then
            # pypy
            virtualenv_libpath="${PYENV_ROOT}/versions/${version}/lib-python"
          else
            virtualenv_libpath="${PYENV_ROOT}/versions/${version}/lib"
          fi
        fi
        no_global_site_packages="$(find "${virtualenv_libpath}/" -maxdepth 2 -type f -and -name "no-global-site-packages.txt" 2>/dev/null | head -1)"
        if [ ! -f "${no_global_site_packages}" ]; then
          include_system_site_packages=1
        fi
        virtualenv_orig_prefix="$(find "${virtualenv_libpath}/" -maxdepth 2 -type f -and -name "orig-prefix.txt" 2>/dev/null | head -1)"
        if [ -f "${virtualenv_orig_prefix}" ]; then
          virtualenv_prefix="$(cat "${virtualenv_orig_prefix}" 2>/dev/null || true)"
        fi
      fi
      if [ -n "${include_system_site_packages}" ] && [ -n "${virtualenv_prefix}" ]; then
        # virtualenv is created with `--system-site-packages`
        virtualenv_command_path="${virtualenv_prefix}/bin/${PYENV_COMMAND_PATH##*/}"
        if [ -x "${virtualenv_command_path}" ]; then
          PYENV_COMMAND_PATH="${virtualenv_command_path}"
        fi
      fi
    fi
  fi
fi
