#!/usr/bin/env bash

# wrapper for smaller output from __rvm_log_command
__rvm_rm_rf()
{
  __rvm_rm_rf_verbose "$@"
}
#
# \rm -rf with *some* safeguards in place.
#
__rvm_rm_rf_verbose()
{
  typeset target
  target="${1%%+(/|.)}"

  #NOTE: RVM Requires extended globbing shell feature turned on.
  if
    [[ -n "${ZSH_VERSION:-}" ]]
  then
    setopt extendedglob
  elif
    [[ -n "${BASH_VERSION:-}" ]]
  then
    shopt -s extglob
  else
    rvm_error "What the heck kind of shell are you running here???"
  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))
      rvm_debug "__rvm_rm_rf target is not valid - can not remove"
      return 1
      ;;
    (*)
      [[ -n "${target}" ]] ||
      {
        rvm_debug "__rvm_rm_rf target not given"
        return 1
      }
      if
        [[ -d "${target}" ]]  # Directory
      then
        \rm -rf "${target}" ||
        {
          typeset ret=$?
          rvm_debug "__rvm_rm_rf error removing target dir '${target}'."
          return $ret
        }
      elif
        [[ -f "${target}" || -L "${target}" ]] # File / Symbolic Link
      then
        \rm -f "${target}" ||
        {
          typeset ret=$?
          rvm_debug "__rvm_rm_rf error removing target file/link '${target}'."
          return $ret
        }
      else
        rvm_debug "__rvm_rm_rf already gone: $*"
        return 0 # already gone!?
      fi
      ;;
  esac
}

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

  typeset response

  response="no"
  read response

  if [[ "yes" == "$response" ]]
  then
    __rvm_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),
# or the current process id.
__rvm_cleanup_tmp()
{
  if [[ -d "${rvm_tmp_path}/" ]]
  then
    case "${rvm_tmp_path%\/}" in
      *tmp)
        __rvm_rm_rf "${rvm_tmp_path}/${1:-$$}*"
        ;;
    esac
  fi
  return 0
}
