#!/usr/bin/env bash

goruby_install()
{
  unset GEM_HOME GEM_PATH MY_RUBY_HOME IRBRC
  export PATH

  __rvm_remove_rvm_from_path
  __rvm_conditionally_add_bin_path

  builtin hash -r

  rvm_ruby_home="$rvm_rubies_path/$rvm_ruby_interpreter"

  __rvm_fetch_ruby
  __rvm_apply_patches ||
  {
    result=$?
    rvm_error "There has been an error while trying to apply patches to goruby.  \nHalting the installation."
    exit $result
  }

  #__rvm_cd "${rvm_src_path}/$rvm_ruby_string/configure"

  [[ -s "${rvm_src_path}/$rvm_ruby_string/configure" ]] ||
    __rvm_run "autoreconf" "__rvm_autoreconf" "Running autoreconf"

  if [[ -s ./Makefile && -z "$rvm_reconfigure_flag" ]]
  then
    if (( ${rvm_debug_flag:=0} > 0 ))
    then
      rvm_debug "Skipping configure step, Makefile exists so configure must have already been run."
    fi
  elif [[ -n "$rvm_ruby_configure" ]]
  then
    __rvm_run "configure" "$rvm_ruby_configure"
    result=$?

    if (( result > 0 ))
    then
      rvm_error "There has been an error while trying to configure the source.  \nHalting the installation."
      exit $result
    fi

  elif [[ -s ./configure ]]
  then
    __rvm_log_command "configure" "$rvm_ruby_string - #configuring" \
      "${rvm_configure_env[@]}" ./configure --prefix="$rvm_ruby_home" "${rvm_configure_flags[@]}"
    result=$?

    if (( result > 0 ))
    then
      rvm_error "There has been an error while trying to configure the source.  \nHalting the installation."
      exit $result
    fi

  else
    rvm_error "Skipping configure step, 'configure' script does not exist, did autoreconf not run successfully?"
  fi

  : rvm_ruby_make:${rvm_ruby_make:=make}

  __rvm_log_command "make" "Compiling $rvm_ruby_string, this may take a while depending on your cpu(s)" \
    $rvm_ruby_make golf "${rvm_make_flags[@]}"
  result=$?

  if (( result > 0 ))
  then
    rvm_error "There has been an error while trying to run make.  \nHalting the installation."
    exit $result
  fi

  rvm_ruby_make_install=${rvm_ruby_make_install:-"__rvm_make install"}

  __rvm_run "install" "$rvm_ruby_make_install" "Installing $rvm_ruby_string"
  result=$?

  if (( result > 0 ))
  then
    rvm_error "There has been an error while trying to run make install.  \nHalting the installation."
    exit $result
  fi

  rvm_log "Installation of $rvm_ruby_string is complete."

  export GEM_HOME="$rvm_ruby_gem_home"
  export GEM_PATH="$rvm_ruby_gem_path"

  \rm $rvm_ruby_home/bin/ruby
  ln -s $rvm_ruby_home/bin/goruby $rvm_ruby_home/bin/ruby

  __rvm_initial_gemsets_create &&
  __rvm_post_install &&
  __rvm_fetch_ruby_cleanup
}
