#!/bin/sh

# Uninstaller script for GHC.framework 
# (currently only for system volume installations)

INSTALL_DEST=/Library/Frameworks
INSTALL_BASE=/

# Turn off things that might make /usr/bin/ls give funky output
unset CLICOLOR
unset CLICOLOR_FORCE
unset LSCOLORS

if [ ${INSTALL_BASE} = / ]; then
  INSTALL_BASE=/usr
fi
INSTALL_BIN=${INSTALL_BASE}/bin
INSTALL_MAN1=${INSTALL_BASE}/share/man/man1
INSTALL_HTML=${INSTALL_BASE}/share/doc

if [ ! -x ${INSTALL_DEST}/GHC.framework ]; then
  echo "${INSTALL_DEST}/GHC.framework does not exit"
  exit 1
fi

if [ ${USER} != root ]; then
  echo "GHC.framework installer must be run with admin privileges"
  echo "Prefix command by 'sudo'"
  exit 1
fi

FRAMEWORK_DIRECTORY="$INSTALL_DEST/GHC.framework"
VERSIONS_DIRECTORY="$FRAMEWORK_DIRECTORY/Versions"

MY_VERSION=@FRAMEWORK_VERSION@
MY_DIRECTORY="$VERSIONS_DIRECTORY/$MY_VERSION"

CURRENT_DIRECTORY="$VERSIONS_DIRECTORY/Current"
CURRENT_VERSION=`readlink "$CURRENT_DIRECTORY"`

removeLinksFrom () {
    for f in `ls -1 "$MY_DIRECTORY/$1"`
    do
        qf="$1/$f"
        # Only remove if it is a link to our version. e.g. /usr/bin/ghc
        # will only be removed if we are the current version, but
        # /usr/bin/ghc-7.0.1 will be removed even if ghc-7.2.1 is the
        # current version.
        l=`readlink "$qf" | grep "GHC.framework/Versions/$MY_VERSION"`
        if [ "$l" != "" ]
        then
            rm -f "$qf"
        fi
    done
}

removeLinksFrom /usr/bin
removeLinksFrom /usr/share/man/man1
removeLinksFrom /usr/share/doc

echo "Removing $MY_DIRECTORY"
rm -rf "$MY_DIRECTORY"

if [ "$CURRENT_VERSION" = "$MY_VERSION" ]
then
    rm -f "$CURRENT_DIRECTORY"

    # This isn't ideal, but it's a vague approximation to
    # "the most recent version":
    NEW_VERSION=`ls -1 "$VERSIONS_DIRECTORY" | tail -1`
    if [ "$NEW_VERSION" = "" ]
    then
        echo "Removing $FRAMEWORK_DIRECTORY"
        rm -rf "$FRAMEWORK_DIRECTORY"
    else
        ln -s "$NEW_VERSION" "$CURRENT_DIRECTORY"
        NEW_CREATE_LINKS="$VERSIONS_DIRECTORY/$NEW_VERSION/Tools/create-links"
        if [ -f "$NEW_CREATE_LINKS" ]
        then
            sh "$NEW_CREATE_LINKS" unused /Library/Frameworks /
        fi
    fi
fi

echo "Removing package receipt"
# The first is for Leopard packages and the second for Tiger packages.
rm -f "/Library/Receipts/boms/org.haskell.ghc.$MY_VERSION.bom"
rm -rf "/Library/Receipts/ghc.$MY_VERSION.pkg"

echo "Done."

