#! /bin/sh
# Shamelessly stolen and extended mega-hack from ghc, nhc98, c2hs, autoconf, ...
# to find GHC's libdir.

# "ghc" is the default name for GHC
if test $# = 0 ; then
  HC=ghc
  HC_PROG=$HC
else
  HC="$@"
  HC_PROG=$1 # Takes care of the fact that there could be args
fi

# Determine PATH separator
rm -f conftest.sh
echo "#! /bin/sh" >conftest.sh
echo  "exit 0"   >>conftest.sh
chmod +x conftest.sh
if { (PATH=".;."; conftest.sh) 2> /dev/null ; }; then
  PATH_SEPARATOR=';'
else
  PATH_SEPARATOR=:
fi
rm -f conftest.sh

# Get full path for HC, taking care of a possible .exe extension
case "$HC" in
  [\\/]* | ?:[\\/]*)
    FULL_PATH_TO_GHC="$HC" # Let the user override the test with a path.
    ;;
  *)
    SAVE_IFS=$IFS; IFS=$PATH_SEPARATOR
    DUMMY="$PATH"
    for dir in $DUMMY; do
      IFS=$SAVE_IFS
      test -z "$dir" && dir=.
      if test -f "$dir/$HC_PROG"; then
        FULL_PATH_TO_GHC="$dir/$HC_PROG"
        break
      fi
    done
    ;;
esac

# Do we run under cygwin?
IS_CYGWIN=no

case "$FULL_PATH_TO_GHC" in
  /cygdrive/*) IS_CYGWIN=yes ;;
  *) ;;
esac

if  test "$IS_CYGWIN" = "no" ; then
   case `uname | tr a-z A-Z` in
     CYGWIN*|MINGW*) IS_CYGWIN=yes ;;
     *) ;;
   esac
fi

if test "$IS_CYGWIN" = "yes" ; then
  # Under WinDoze, ghc itself is an exe, not a grep-able script. We assume the
  # libdir just above the bin dir containing the ghc executable then.
   GHC_LIB_DIR=`echo "$FULL_PATH_TO_GHC" | sed 's,^\(.*\)/bin/ghc.*,\1,'`
else
  GHC_VERSION=`"$HC" --version 2>&1 | sed -n -e 's/, patchlevel *\([0-9]\)/.\1/;s/.* version \([0-9][0-9.]*\).*/\1/p'`
  test -z "$GHC_VERSION" && GHC_VERSION=unknown
  GHC_MAJOR_VERSION=`echo $GHC_VERSION | sed -e 's/^\([0-9]\).*/\1/'`
  # GHC_MINOR_VERSION=`echo $GHC_VERSION | sed -e 's/^[0-9]\.\([0-9]*\).*/\1/'`
  # GHC_PATCHLEVEL=`echo $GHC_VERSION | sed -n -e 's/^[0-9]\.[0-9]*\.\([0-9]*\)/\1/p'`

  if test "$GHC_MAJOR_VERSION" -lt 5 ; then
    GHC_LIB_DIR=`grep '^\$libdir=' "$FULL_PATH_TO_GHC" | head -1 | sed 's/^\$libdir=[^/]*\(.*\).;/\1/'`
  else
    GHC_LIB_DIR=`grep '^libdir=' "$FULL_PATH_TO_GHC" | head -1 | sed 's/^libdir=.\(.*\)./\1/'`
    test -z "$GHC_LIB_DIR" && GHC_LIB_DIR=`grep '^TOPDIROPT=' "$FULL_PATH_TO_GHC" | sed 's/^TOPDIROPT=.-B\(.*\).;/\1/'`
  fi
fi

echo $GHC_LIB_DIR

# We don't need the following lines, because we always assume the first case.
#
# GHC_IMPORTS_DIR="$GHC_LIB_DIR/imports"
# test -d "$GHC_IMPORTS_DIR" || GHC_IMPORTS_DIR="$GHC_LIB_DIR/lib/imports"
