#!/usr/bin/env bash

# rvm : Ruby enVironment Manager
# http://rvm.beginrescueend.com
# http://github.com/wayneeseguin/rvm

grep -q '^rvm ()' < <( declare -f ) # Is RVM is a shell function?

if [[ $? -gt 0 || ${rvm_reload_flag:-0} -eq 1 ]] ; then

  if [[ ${rvm_ignore_rvmrc:-0} -eq 0 ]]; then

    for rvmrc in /etc/rvmrc "$HOME/.rvmrc" ; do

      if [[ -f "$rvmrc" ]] ; then

        if \grep -q '^\s*rvm .*$' $rvmrc ; then

          printf "\nError: $rvmrc is for rvm settings only.\nrvm CLI may NOT be called from within $rvmrc. \nSkipping the loading of $rvmrc"

          return 1

        else

          source "$rvmrc"

        fi

      fi

    done

  fi

  # Set the default sandboxed value.
  if [[ -z "$rvm_selfcontained" ]]; then

    if [[ "root" = "$(whoami)" || -n "$rvm_prefix" && "$rvm_prefix" != "$HOME"/* ]]; then

      rvm_selfcontained=0

    else

      rvm_selfcontained=1

    fi

  fi

  if [[ -z "$rvm_prefix" ]] ; then

    if [[ "$rvm_selfcontained" = "0" ]] ; then

      rvm_prefix="/usr/local/"

    else

      rvm_prefix="$HOME/."

    fi

  fi

  # Fix rvm_prefix changes.
  echo "$rvm_prefix" | \grep -vq '\(\/\|\.\)$' && [[ -d "$rvm_prefix/rvm/scripts" ]]

  rvm_prefix_needs_trailing_slash="$?"

  if [[ "$rvm_prefix" = "/usr/local" || "$rvm_prefix_needs_trailing_slash" = "0" ]]; then

    rvm_prefix="$rvm_prefix/"

  fi

  if [[ -z "$rvm_path" ]] ; then
    rvm_path="${rvm_prefix}rvm"
  fi

  if [[ -d "$rvm_path" ]] ; then

    for script in array utility initialize version selector cli cd override_gem ; do

      if [[ -f "$rvm_path/scripts/$script" ]] ; then

        source "$rvm_path/scripts/$script"

      else

        "$rvm_path/scripts/log" "error" \
          "RVM: Could not source script '$rvm_path/scripts/$script', file does not exist. RVM will likely not work as expected."

      fi
    done

    rvm_version="$(awk '/:/{printf $NF"."}' "$rvm_path/lib/VERSION.yml")"

    export rvm_version="${rvm_version/%.}"

    alias rvm-restart="source '${rvm_path}/scripts/rvm'"

    if ! command -v ruby >/dev/null 2>&1 || command -v ruby | \grep -v rvm >/dev/null ; then

      if [[ -s "$rvm_path/environments/default" ]] ; then

        source "$rvm_path/environments/default"

      fi

    fi

    # Makes sure rvm_bin_path is in PATH atleast once.
    __rvm_conditionally_add_bin_path

  else
    printf "\n\$rvm_path is not set. rvm cannot load."
  fi

  unset rvm_prefix_needs_trailing_slash rvm_bin_path rvm_man_path rvm_rc_files rvm_gems_path rvm_gems_cache_path rvm_interactive_flag rvm_gems_path rvm_project_rvmrc_default rvm_gemset_separator

fi

if [[ ${rvm_interactive_flag:-0} -gt 0 ]]; then
  cd .
fi
