#!/usr/bin/env bash
#
# Summary: Download ruby binaries directly from RVM repo
#
# Usage: rbenv download <ruby-version>

set -e
[ -n "$RBENV_DEBUG" ] && set -x

# Optional: Abort with usage line when called with invalid arguments
# (replace COMMAND with the name of this command)
if [ -z "$1" ]; then
  rbenv-help --usage download >&2
  exit 1
fi

RVM_BINARIES_BASE="http://rvm.io/binaries"
RUBIES_ROOT="${RBENV_ROOT}/versions"

source "$(dirname $BASH_SOURCE)/../lib/rvm_import.sh"
source "$(dirname $BASH_SOURCE)/../lib/functions.sh"

detect_system

ruby_version=$1
package_url="${RVM_BINARIES_BASE}/${SYSTEM_NAME}/${SYSTEM_VERSION}/${SYSTEM_ARCH}/ruby-${ruby_version}.tar.bz2"
package_url=`echo $package_url | awk '{print tolower($0)}'`

echo "Download and extract ruby ${ruby_version} from RVM repository"

if ! check_url $package_url; then
  echo "${url} cannot be reached" >&2
  echo "Cannot found a built version of ruby '${ruby_version}' compiled for your current system: ${SYSTEM_NAME} ${SYSTEM_ARCH} (${SYSTEM_VERSION})" >&2
  exit 1
fi

erase_folder_if_exist "${RUBIES_ROOT}/${ruby_version}"
download_and_extract_package $package_url $RUBIES_ROOT
rename_folder_if_exist "${RUBIES_ROOT}/ruby-${ruby_version}" "${RUBIES_ROOT}/${ruby_version}"

echo "Ruby ${ruby_version} has been installed"
