#!/usr/bin/env bash
set -e
[ -n "$RBENV_DEBUG" ] && set -x

if [ "$1" == '--version' ]; then
  echo '0.3.0'
  exit 0
fi

if ! which update-alternatives >/dev/null; then
  echo "Sorry, it seems like you do not have update-alternatives available on your PATH."
  echo "Are you sure this is a Debian (or derivative) system?"
  exit 1
fi

update-alternatives --query ruby | sed -e '
  1,/^$/ d
  /^Priority:/ d
  /^Slaves:/ d
  s/^Alternative: \(.*\)/master \1/
  /\/usr\/bin/ !d
' |
while read command; do
  case "$command" in
    master*)
      master=$(echo "$command" | awk '{print $2}')
      version=$($master -e 'puts(((defined?(RUBY_ENGINE) && RUBY_ENGINE != "ruby") && RUBY_ENGINE + "-" || "") + (defined?(Rubinius) && Rubinius::VERSION || (defined?(JRUBY_VERSION) && JRUBY_VERSION) || RUBY_VERSION))')-debian
      if [ -d "${RBENV_ROOT}/versions/$version" ]; then
        skip=true
        echo "Skipping $version, it already exists"
      else
        skip=false
        rm -rf "${RBENV_ROOT}/versions/$version"
        mkdir -p "${RBENV_ROOT}/versions/$version/bin"
        ln -s "$master" "${RBENV_ROOT}/versions/$version/bin/ruby"
        ln -s "${master/ruby/gem}" "${RBENV_ROOT}/versions/$version/bin/gem"
        echo "Added $version"
      fi
      ;;
    *)
      if [ "$skip" = 'false' ]; then
        prog=$(echo "$command" | awk '{print $1}')
        target=$(echo "$command" | awk '{print $2}')
        ln -s "$target" "${RBENV_ROOT}/versions/$version/bin/$prog"
      fi
      ;;
  esac
done
