#!/bin/sh

# guess installation directory
if test -e "/usr/local/wxhaskell/bin/wx.pkg"; then
  installdir="/usr/local/wxhaskell"
else if test -e "./wx.pkg"; then
  installdir=".."
else
  installdir="/usr/local"
fi
fi

# parse command-line arguments
while : ; do
  # put optional argument in the $arg variable
  case "$1" in
   -*=*) arg=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'` ;;
   *)    arg= ;;
  esac

  # match on the arguments
  case "$1" in
    "") break;;	
    -installdir=*|--installdir=*)
       installdir="$arg";;
    -?|--help)
       echo "usage:"
       echo "  wxhaskell-register  [--installdir=<dir>]"
       exit 1;;
    *) echo "error:" 1>&2
       echo "  Unknown option \"$1\"." 1>&2
       echo "" 1>&2
       echo "usage:" 1>&2
       echo "  wxhaskell-register  [--installdir=<dir>]" 1>&2
       echo "" 1>&2
       exit 2;;
  esac
  shift
done

# set libdir/bindir
libdir="${installdir}/lib"
bindir="${installdir}/bin"

# test if package files are found.
if test ! -e "${bindir}/wx.pkg"; then
  echo "error: " 1>&2
  echo "  Unable to find wxhaskell packages: ${bindir}/wx.pkg" 1>&2
  echo "  Please specify the installation directory on the command line." 1>&2
  echo "  For example: wxhaskell-register --installdir=/usr/local/wxhaskell" 1>&2
  echo "" 1>&2
  exit 2
fi

# register the packages.
if ghc-pkg list > /dev/null 2> /dev/null; then
 # ghc-pkg 6.4 +
 cat ${bindir}/wxcore.pkg | sed -e "s|\${wxhlibdir}|${libdir}|" | ghc-pkg update -
 cat ${bindir}/wx.pkg | sed -e "s|\${wxhlibdir}|${libdir}|" | ghc-pkg update -
else
 # pre ghc-pkg 6.4
 env wxhlibdir=%{wxhlibdir} %{hcpkg}-%{hcversion} -u -i %{wxhlibdir}/wxcore.pkg
 env wxhlibdir=%{wxhlibdir} %{hcpkg}-%{hcversion} -u -i %{wxhlibdir}/wx.pkg
fi
