#!/usr/bin/env bash

set -e

source "${0%/*}/../share/ruby-install/ruby-install.sh"

if [[ $# -eq 0 ]]; then
	known_rubies
	exit
fi

parse_options "$@" || exit $?
load_ruby          || exit $?

if [[ $NO_REINSTALL -eq 1 ]] && [[ -x "$INSTALL_DIR/bin/ruby" ]]; then
	log "Ruby is already installed into $INSTALL_DIR"
	exit
fi

log "Installing $RUBY $RUBY_VERSION into $INSTALL_DIR ..."

pre_install || fail "Pre-install tasks failed!"

if [[ ! $NO_INSTALL_DEPS -eq 1 ]]; then
	install_deps || fail "Installing dependencies failed!"
fi

if [[ ! $NO_DOWNLOAD -eq 1 ]]; then
	download_ruby || fail "Download of $RUBY_URL failed!"
fi

if [[ ! $NO_VERIFY -eq 1 ]]; then
	verify_ruby || fail "Verification of of $RUBY_ARCHIVE failed!"
fi

extract_ruby   || fail "Unpacking of $RUBY_ARCHIVE failed!"
download_patches || fail "Fetching patches $PATCHES failed!"
apply_patches  || fail "Patching $RUBY $RUBY_VERSION failed!"
cd "$SRC_DIR/$RUBY_SRC_DIR"
configure_ruby || fail "Configuration of $RUBY $RUBY_VERSION failed!"
compile_ruby   || fail "Compiling $RUBY $RUBY_VERSION failed!"
install_ruby   || fail "Installation of $RUBY $RUBY_VERSION failed!"
post_install   || fail "Post-install tasks failed!"

log "Successfully installed $RUBY $RUBY_VERSION into $INSTALL_DIR"
