#!/usr/bin/env bash

function bundle_not_found()
{
  printf "%b" "$(tput setaf 1)ERROR: Gem bundler is not installed, run \`gem install bundler\` first.$(tput sgr0)\n"
  exit 127
}

function rvm_ruby_not_used()
{
  printf "%b" "$(tput setaf 1)ERROR: RVM Ruby not used, run \`rvm use ${1##*/}\` first.$(tput sgr0)\n"
  exit 127
}

if
  [[ -n "${GEM_HOME:-}" && -n "${GEM_PATH:-}" ]]
then
  # in rvm warn about missing gem
  bundle_not_found
else
  # remove rvm/bin from PATH
  current_bundle="$(dirname $(which $0))"
  export PATH
  PATH=":${PATH}:"
  PATH="${PATH//:${current_bundle}:/:}"
  PATH="${PATH#:}"
  PATH="${PATH%:}"

  if
    [[ -z "${rvm_path:-}" ]] ||
    ! \which ruby 2>/dev/null | GREP_OPTIONS="" \grep "$rvm_path" >/dev/null
  then
    rvm_ruby_not_used $( gem env gemhome 2>/dev/null || echo ruby )
  elif
    [[ -n "${current_bundle}" ]] && builtin command -v bundle >/dev/null 2>&1
  then
    builtin command bundle "$@"
  else
    bundle_not_found
  fi
fi
