#!/bin/sh

set -e

update-alternatives --remove-all ruby 2>/dev/null || true
update-alternatives --remove-all gem 2>/dev/null || true

version=@@DEBIAN_DEFAULT_RUBY_VERSION@@

# restore the default version overwriting any change made by
# update-alternatives
for program in @@DEBIAN_RUBY_PROGRAMS@@; do
  target=$(readlink -f /usr/bin/$program)
  if [ ! -e /usr/bin/$program -o "$target" = /usr/bin/${program}1.8 -o "$target" = /usr/bin/${program}1.9.1 ]
  then
    echo "Fixing symlink /usr/bin/$program -> $program$version"
    ln -sf $program$version /usr/bin/$program
  fi
done

# this is a horrible hack, but will prevent reconfiguration of ruby1.8 or
# ruby1.9.1 from re-adding the alternatives entries.
for package in ruby1.8 ruby1.9.1; do
  postinst=/var/lib/dpkg/info/$package.postinst
  if [ -e $postinst ]
  then
    sed -i -e 's/^\s*update-alternatives/: &/' $postinst
  fi
done

#DEBHELPER#
