#!/usr/bin/env bash
#
# This is a wrapper to properly execute Vagrant within the embedded
# Vagrant installation directory. This sets up proper environmental variables
# so that everything loads and compiles to proper directories.

for r in ruby32 ruby31 ruby30 ruby27 ruby26; do
  # not all ruby versions are guaranteed to be installed
  if ! command -v "${r}" >/dev/null 2>&1; then
    continue
  fi

  VAGRANT_DIR="$( "${r}" -e 'print Gem::default_path[-1] + "/gems/vagrant-@VAGRANT_VERSION@"' )"

  # Export the VAGRANT_EXECUTABLE so that pre-rubygems can optimize a bit
  export VAGRANT_EXECUTABLE="${VAGRANT_DIR}/bin/vagrant"

  if [ -f ${VAGRANT_EXECUTABLE} ] ;then
    ruby="${r}"
    break
  fi
done

if [ -z ${ruby} ]; then
  echo "Error: failed to find any usable ruby"
  exit 1
fi

# Export GEM_HOME based on VAGRANT_HOME
#
# This needs to be set because Bundler includes gem paths
# from RubyGems' Gem.paths.
if [ -z ${VAGRANT_HOME} ]; then
  VAGRANT_HOME="~/.vagrant.d"
fi
export GEM_HOME="${VAGRANT_HOME}/gems"

# SSL certs
export SSL_CERT_FILE="/etc/ssl/certs/ca-certificates.crt"

# Export an environmental variable to say we're in a Vagrant
# installer created environment.
export VAGRANT_INSTALLER_ENV=1

# This is currently used only in Vagrant::Plugin::Manager.system_plugins_file
# to locate plugins configuration file.
export VAGRANT_INSTALLER_EMBEDDED_DIR="/var/lib/vagrant"
export VAGRANT_INSTALLER_VERSION=2

# Export the OS as an environmental variable that Vagrant can access
# so that it can behave better.
export VAGRANT_DETECTED_OS="$(uname -s 2>/dev/null)"

# Allow to install plugins even with deps in different slots (Bug #628648)
export VAGRANT_DISABLE_STRICT_DEPENDENCY_ENFORCEMENT=1

# Make it work with rvm (Bugs #474476 #628648)
unset GEM_HOME GEM_PATH

# Call the actual Vagrant bin with our arguments
exec "${ruby}" "${VAGRANT_EXECUTABLE}" "$@"
