#!/usr/bin/env bash
# Summary: Detect the file that sets the current jenv version
set -e
[ -n "$JENV_DEBUG" ] && set -x

find_local_version_file() {
  local root="$1"
  while [ -n "$root" ]; do
    if [ -e "${root}/.java-version" ]; then
      echo "${root}/.java-version"
      exit
    elif [ -e "${root}/.jenv-version" ]; then
      echo "${root}/.jenv-version"
      exit
    fi
    root="${root%/*}"
  done
}

find_local_version_file "$JENV_DIR"
[ "$JENV_DIR" = "$PWD" ] || find_local_version_file "$PWD"

global_version_file="${JENV_ROOT}/version"

if [ -e "$global_version_file" ]; then
  echo "$global_version_file"
elif [ -e "${JENV_ROOT}/global" ]; then
  echo "${JENV_ROOT}/global"
elif [ -e "${JENV_ROOT}/default" ]; then
  echo "${JENV_ROOT}/default"
else
  echo "$global_version_file"
fi
