#!/usr/bin/env bash

#
# rm -rf with *some* safeguards in place.
#
__rvm_rm_rf()
{
  local result=1 target="${1%%+(/|.)}"

  #NOTE: RVM Requires extended globbing shell feature turned on.
  if [[ -n "${ZSH_VERSION:-}" ]] ; then
    setopt extendedglob
  else
    if [[ -n "${BASH_VERSION:-}" ]] ; then
      shopt -s extglob # Extended globs
    else
      printf "%s\n" "What the heck kind of shell are you running here???"
    fi
  fi

  case "${target}" in

    (*(/|.)@(|/Applications|/Developer|/Guides|/Information|/Library|/Network|/System|/User|/Users|/Volumes|/backups|/bdsm|/bin|/boot|/cores|/data|/dev|/etc|/home|/lib|/lib64|/mach_kernel|/media|/misc|/mnt|/net|/opt|/private|/proc|/root|/sbin|/selinux|/srv|/sys|/tmp|/usr|/var))
        false
      ;;

    (*)
      if [[ -n "${target}"  ]] ; then

        if [[ -d "${target}" ]] ; then # Directory
          \rm -rf "${target}"
          result=0
        elif [[ -f "${target}" || -L "${target}" ]]; then # File / Symbolic Link
          \rm -f "${target}"
          result=0
        else
          result=0 # already gone!?
        fi

      fi
      ;;
  esac

  return $result
}

__rvm_reboot()
{
    rvm_warn "Do you wish to reboot rvm?\n('yes', or 'no')> "

  local response="no"

  read response

  if [[ "yes" == "$response" ]] ; then
    builtin cd $rvm_path

    command -v __rvm_reset >> /dev/null 2>&1 || \
      source "$rvm_scripts_path/functions/reset"
    __rvm_reset

    mv "$rvm_archives_path" "$HOME/.archives"

    if [[ "/" == "$rvm_path" ]] ; then
      rvm_error "remove '/' ?!... NO!"
    else
      if [[ -d "$rvm_path" ]] ; then __rvm_rm_rf "$rvm_path" ; fi
    fi

    gem install rvm $rvm_gem_options

    "$rvm_scripts_path/get" latest

    source "$rvm_scripts_path/rvm"
  else
    rvm_log "Carry on then..."
  fi

  return 0
}

# Cleans up temp folders for a given prefix ($1),
# typically the current process id.
__rvm_cleanup_tmp()
{
  result=$? # Capture last command status

  [[ -z "${1:-""}" ]] && return 1

  if [[ -d "${rvm_tmp_path}/" ]]; then

    case "${rvm_tmp_path%\/}" in
      *tmp)
        __rvm_rm_rf "${rvm_tmp_path}/${1}"
        ;;
    esac


  fi

  return $result
}

