#!/bin/sh

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

INSTALL_DEST=/Library/Frameworks
INSTALL_BASE=/

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

VERSIONS=(`ls ${INSTALL_DEST}/GHC.framework/Versions`)
NO_VERSIONS=${#VERSIONS[@]}

if [ ${VERSIONS[${NO_VERSIONS}-1]} != Current ]; then
  echo "Fatal error: last version should be Current"
  echo "Found versions: ${VERSIONS[@]}"
  exit 1
fi
CURRENT_PHYS=`cd /Library/Frameworks/GHC.framework/Versions/Current; pwd -P`
CURRENT=`basename ${CURRENT_PHYS}`

if [ ${NO_VERSIONS} -ne 2 ]; then
  echo "Multiple versions of GHC.framework are currently installed."
  echo "This uninstaller removes GHC.framework entirely and should only"
  echo "be used if there is exactly one version."
  echo
  echo "To remove individual old versions, simply delete the directory"
  echo "${INSTALL_DEST}/GHC.framework/Versions/VERSION_TO_REMOVE"
  echo
  echo "Found versions: ${VERSIONS[@]}(= ${CURRENT})"
  exit 1
fi

echo "Removing symbolic links into GHC.framework"
for thisfile in ${INSTALL_BIN}/*; do
  if ls -l "${thisfile}" | grep -q GHC.framework/Versions; then
    rm -f "${thisfile}"
  fi
done
for thisfile in ${INSTALL_MAN1}/*; do
  if ls -l "${thisfile}" | grep -q GHC.framework/Versions; then
    rm -f "${thisfile}"
  fi
done
for thisfile in ${INSTALL_HTML}/*; do
  if ls -l "${thisfile}" | grep -q GHC.framework/Versions; then
    rm -f "${thisfile}"
  fi
done

echo "Removing ${INSTALL_DEST}/GHC.framework"
rm -rf ${INSTALL_DEST}/GHC.framework

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

echo "${INSTALL_DEST}/GHC.framework has been purged!"
