#!/bin/sh

#------------------------------------------------------------------------
#  Configure script for wxHaskell
#
#  Copyright (c) 2003, 2004 Daan Leijen.
#  Copyright (c) 2006 Jeremy O'Donoghue (jeremy.odonoghue@gmail.com)
#
#  See license.txt for details.
#------------------------------------------------------------------------

#--------------------------------------------------------------------
# Versioning
#--------------------------------------------------------------------
version="0.11.1"
release="0"

#--------------------------------------------------------------------
# Variables
#--------------------------------------------------------------------

# install
enablestrip="no"
enableupx="no"
withmsc="no"
wxclibname="wxc"
configflags="$*"

# haskell
hc="ghc"
hcflags=""
hcpkg="ghc-pkg"
hcopt=""
hcprof="-prof"
hcpkgopt=""
hcpkglocal=""
hdoc="haddock"

# directories
topdir="`pwd`"
prefix="/usr"
execprefix=""
libdir=""
sharedprefix="<libdir>"

# dll extension and lib prefix
exe=""
dll=".so"
lib="lib"

# c++ compiler, flags and libraries
cxx="c++"
wxwincxxflags=""
wxwinlibs=""

# wxwidgets
wxconfig="wx-config"
wxtoolkit=""
wxversion=""
extraldopts=""

# check architecture, for mac os x
architecture=""

# extras
withopengl="no"
withmediactrl="no"
withcontrib="no"
wxccontrib=""

#--------------------------------------------------------------------
# Function "findprogram": find a program in the path
#--------------------------------------------------------------------
findprogram () {
  if test -f $1; then return 0; fi
  saveIFS="$IFS"
  IFS=':'
  for dir in $PATH; do
    if test -z "$dir"; then dir=.; fi
    if test -f $dir/$1; then 
      IFS="$saveIFS"
      return 0
    fi
  done
  IFS="$saveIFS"
  return 1
}

#--------------------------------------------------------------------
# wx-config guess
#--------------------------------------------------------------------

# macosx: wx-config might be not in the path
if test -x "/usr/local/wxhaskell/bin/wx-config"; then
  wxconfig="/usr/local/wxhaskell/bin/wx-config"
else
  if findprogram "$wxconfig"; then :; else
    if test -x "/usr/local/bin/wx-config"; then
      wxconfig="/usr/local/bin/wx-config"
    fi
  fi
fi

#--------------------------------------------------------------------
# Pre-process arguments
#--------------------------------------------------------------------

arguments_raw=$@	# raw arguments	
arguments_exp=""	# arguments with "--cache" expanded
arguments=""		# final arguments (with "wxconfig" and "withmsc" removed)
usecached="no"

# expand the "--cache" argument
expand_cache () 
{
  while : ; do
    case "$1" in
     "") break;;
     -cache|--cache)
        if test -f "config/cache.txt"; then
	  usecached="yes"
	  cached=`cat config/cache.txt`
	  arguments_exp="$arguments_exp $cached"
	else
	  # nothing cached yet
	  echo "warning:"
	  echo " Option --cache given, but no previous configuration was present."
	  echo ""	  
	fi;;
     *)
        arguments_exp="$arguments_exp $1";;    # save argument
    esac
    shift # next argument
  done
  return 0
}

expand_cache $arguments_raw	# set $arguments_exp
if test "$usecached" = "yes"; then
 echo "expanded arguments:"
 echo " $arguments_exp"
 echo ""
fi

# preprocess certain options that improve the guesses
preprocess_args () 
{
  arg=""
  while : ; do
    # put optional argument in the $arg variable
    case "$1" in
     -*=*) arg=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'` 
	   arg=`eval echo $arg`;;  # expand ~
     *)    arg="";;
    esac
  
    # check argument
    case "$1" in
     "") break;;
     -wx-config=*|--wx-config=*)
	wxconfig="$arg";;
     -with-msc|--with-msc)
	withmsc="yes"
	lib=""
	dll=".dll"
	wxtoolkit="msw"
	wxversion="2.8.9";;  # guess?
     *)
        arguments="$arguments $1";;    # save argument
    esac
    shift # next argument
  done
  return 0
}

preprocess_args $arguments_exp  # set $arguments


# set cache argument for help options
if test -f "config/cache.txt"; then
 cache=`cat config/cache.txt`
else
 cache=""
fi


#--------------------------------------------------------------------
# Improve guesses
#--------------------------------------------------------------------
# improve guess prefix
if test -d "/usr/local"; then
  prefix="/usr/local"
fi

# does 'cygpath' exist?
cygpathfound=""
if findprogram "cygpath"; then
  cygpathfound="yes"
fi

# guess username
if test "$USERNAME"; then
  username="$USERNAME"
else if test "$HOME"; then
  username=`echo $HOME | sed -e 's|.*[/\\]||'`
else
  username="username"
fi
fi


# improve the guesses if wx-config is present.
if findprogram "$wxconfig"; then
  # improve prefix guess
  prefix="`$wxconfig --prefix`"

  # guess version
  wxversion="`$wxconfig --version`"

  # guess toolkit
  wxtoolkit="`$wxconfig --cxxflags | sed -e 's|.*-D__WX\([A-Z]*\)__.*|\1|'`"
  # to lowercase
  wxtoolkit="`echo "$wxtoolkit" | sed -e 'y|ABCDEFGHIJKLMNOPQRSTUVWXYZ|abcdefghijklmnopqrstuvwxyz|'`"

  # flaky way to guess library extensions
  if test "$wxtoolkit" = "msw"; then
    dll=".dll"
    lib=""
  else if test "$wxtoolkit" = "mac"; then
    dll=".dylib"
    lib="lib"
    architecture=`uname -p`
    # use a standard prefix on MacOS X for the installer
    prefix="/usr/local/wxhaskell"
  fi
  fi

  # guess extra link options
  extraldopts=""		# "`$wxconfig --ldflags`"
  pthread="`$wxconfig --libs | sed -e \"s|.* -pthread .*|yes|\"`"
  if test "$pthread" = "yes"; then
    if test -z "$extraldopts"; then
      extraldopts="-pthread"
    else
      extraldopts="$extraldopts -pthread"
    fi
  fi
else
  if test "$withmsc" != "yes"; then   
    echo "warning:"
    echo " Unable to find wxWidgets configuration ($wxconfig)."
    echo ""
  fi
fi

# initial completion rules
execprefix_doc="<prefix>"
libdir_doc="<exec-prefix>/lib"
wxclib_doc="<libdir>/${lib}wxc${dll}"


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

    # match on the arguments
    case "$1" in
      "") break;;
      -?|--help)
	  echo "usage:"
	  echo " ./configure [options]"
	  echo ""
	  echo "options: [defaults in brackets]"
	  echo " --help                 show this information"
	  echo " --hc=<program>         the haskell compiler [$hc]"
	  echo " --hcpkg=<program>      package compiler [$hcpkg]"
          echo " --hcprof=<flags>       enable profiling (using flags [$hcprof])"
	  echo " --fvia-C               use -fvia-C option"
	  echo " --package-conf=<file>  optional local package configuration [$hcpkglocal]"
	  echo " --user                 use current user's local package database"
	  echo " --global               use global package database"
	  echo " --version=<version>    library version [$version]"
	  echo " --release=<version>    library release version [$release]"
	  echo " --cache                expands into previous configure options"
	  echo "                        [$cache]"
	  echo ""
	  echo "install options:"
	  echo " --prefix=<dir>         install directory [$prefix]"
	  echo " --exec-prefix=<dir>    platform dependent install directory [$execprefix_doc]"
	  echo " --libdir=<dir>         library files install directory [$libdir_doc]"
	  echo " --shared-prefix=<dir>  fixed path prefix for dynamic libraries [$sharedprefix]"
	  echo " --enable-strip         remove symbols from the libraries [$enablestrip]"
	  echo " --enable-upx           compress the dynamic libraries with upx [$enableupx]"
	  echo ""
	  echo "documentation options:"
	  echo " --username=<name>      username on sourceforge [$username]"
	  echo " --haddock=<program>    haddock documentation tool [$hdoc]"
	  echo ""
	  echo "wxwidgets options:"
	  echo " --wx-toolkit=<name>    wxWidgets gui toolkit [$wxtoolkit]"
	  echo " --with-opengl          enable openGL support [$withopengl]"
	  echo " --with-mediactrl       enable mediactrl support [$withmediactrl]"
          echo " --with-contrib         enable contrib libraries support [$withcontrib]"
	  echo " --wx-config=<program>  wxWidgets configure script [$wxconfig]"
	  echo ""
	  echo "platform options:"
	  echo " --dllext=<extension>   dynamic link library extension [$dll]"
	  echo " --libprefix=<prefix>   library prefix [$lib]"
	  echo " --extra-ld-opts=<opts> extra link options [$extraldopts]"
	  echo " --with-msc             compile wxWidgets and wxc with microsoft vc++ [$withmsc]"
	  echo " --wxc-libname=<name>   wxc library base name [$wxclibname]"
	  echo ""
	  exit 1;;

      -cache|--cache)
	  echo "warning:"
	  echo " Ignoring --cache option; this option must be the first (and only) option."
	  echo "";;

      --with-compiler=*)
	  hc="$arg";;
      # This option is deprecated. Use --with-compiler instead.
      --with-hc=*)
	  hc="$arg";;
      -hc=*|--hc=*)
	  hc="$arg";;
      -hcpkg=*|--hcpkg=*)
	  hcpkg="$arg";;
      -hcflags=*|--hcflags=*)
	  hcflags="$arg";;
      -fvia-C|--fvia-C)
	  hcflags="$hcflags -fvia-C";;
      -hcprof|--hcprof)
	  hcprof="$hcprof -auto-all"
	  enableprof="yes";;
      -hcprof=*|--hcprof=*)
	  hcprof="$hcprof $arg"
	  enableprof="yes";;
      -package-conf=*|--package-conf=*)
	  hcpkglocal="$arg";;
      -user|--user)
	  hcpkgopt="--user"
          if test -d "$HOME/.cabal"; then
            prefix="$HOME/.cabal/lib/wxhaskell-$version"
            execprefix="$prefix"
            libprefix="$prefix"
            # TODO: sharedprefix means shared library's directory currently. This is confusing point.
            # sharedprefix="$prefix/share"
            sharedprefix="$prefix/lib"
          fi;;
      -global|--global) ;;       # just for cabal
      -version=*|--version=*)
	  version="$arg";;
      -release=*|--release=*)
	  release="$arg";;

      -prefix=*|--prefix=*)
	  prefix="$arg";;
      -exec-prefix=*|--exec-prefix=*)
	  execprefix="$arg"
	  execprefix_doc="$arg";;
      -bindir=*|--bindir=*)
	  bindir="$arg"
	  bindir_doc="$arg";;
      -libdir=*|--libdir=*)
	  libdir="$arg"
	  libdir_doc="$arg";;
      -datadir=*|--datadir=*) ;;       # just for cabal
      -libexecdir=*|--libexecdir=*) ;; # just for cabal
      -shared-prefix=*|--shared-prefix=*)
	  sharedprefix="$arg";;
      # This option is the same as --hcprof option.
      # But we added this option for repspecting Cabal's option.
      -enable-library-profiling|--enable-library-profiling)
	  hcprof="$hcprof -auto-all"
	  enableprof="yes";;
      # short name for --enable-library-profiling
      # --p works, but -p doesn't work currently. We don't know why.
      -p|--p)
	  hcprof="$hcprof -auto-all"
	  enableprof="yes";;
      -enable-optimization|--enable-optimization)
	  enableoptimization="yes";;
      -enable-optimization=*|--enable-optimization=*)
          hcopt="$arg"
	  enableoptimization="yes";;
      # short name for --enable-optimization
      # --O works, -On works too. But -O doesn't work currently. We don't know why.
      -O|--O)
	  enableoptimization="yes";;
      -O1|--O1)
          hcopt="1"
	  enableoptimization="yes";;
      -O2|--O2)
          hcopt="2"
	  enableoptimization="yes";;
      -enable-split-objs|--enable-split-objs)
	  enablesplitobjs="yes";;
      -enable-strip|--enable-strip)
	  enablestrip="yes";;
      -disable-strip|--disable-strip)
	  enablestrip="no";;
      -enable-upx|--enable-upx)
	  enableupx="yes";;
      -disable-upx|--disable-upx)
	  enableupx="no";;

      -username=*|--username=*)
	  username="$arg";;
      -haddock=*|--haddock=*)
	  hdoc="$arg";;

      -wx-toolkit=*|--wx-toolkit=*)
	  wxtoolkit="$arg";;
      -with-opengl|--with-opengl)
	  withopengl="yes";;
      -with-mediactrl|--with-mediactrl)
	  withmediactrl="yes";;
      -with-contrib|--with-contrib)
	  withcontrib="yes";;
      -wx-config=*|--wx-config=*)
	  echo "warning:"
	  echo " Ignoring --wx-config option; this option must be the first option."
	  echo "";;

      -dllext=*|--dllext=*)
	  dll="$arg"
	  wxclib_doc="<libdir>/${lib}wxc${dll}";;
      -libprefix=*|--libprefix=*)
	  lib="$arg"
	  wxclib_doc="<libdir>/${lib}wxc${dll}";;
      -extra-ld-opts=*|--extra-ld-opts=*)
	  extraldopts="$arg";;
      -with-msc|--with-msc)
	  withmsc="yes"
	  lib=""
	  dll=".dll"
	  wxtoolkit="msw"
	  wxversion="2.8.7";;  # guess?
      -wxc-libname=*|--wxc-libname=*)
	  if test "$withmsc" = "yes"; then
	    wxclibname="$arg"
	  else
	    echo "warning:"
	    echo " Option --wxc-libname is only valid if preceded with --with-msc."
	    echo ""
	  fi;;
     *) echo "error: Unknown option \"$1\". Use \"--help\" to show valid options." 1>&2
	 echo "" 1>&2
	 exit 2;;
    esac

    # process next argument
    shift
  done
  return 0;
}

process_args $arguments

#--------------------------------------------------------------------
# directories
#--------------------------------------------------------------------
# complete arguments
if test -z "$execprefix"; then
  execprefix="$prefix"
fi

if test -z "$libdir"; then
  libdir="$execprefix/lib"
fi

if test "$dll" = ".dll"; then
  exe=".exe"
fi

if test "$sharedprefix" = "<libdir>"; then
  sharedprefix="$libdir"
fi

# add "/" to shared-prefix if not empty or already ending on "/"
if test "$sharedprefix"; then
  case "$sharedprefix" in
    */) ;;
    *) sharedprefix="$sharedprefix/";;
  esac
fi

# normalize the library and imports directory since ghc-pkg doesn't like unix names
if test "$cygpathfound"; then
  libdir="`cygpath -w $libdir | sed -e 's|\\\\|/|g'`"
fi

echo "checking system:"


#--------------------------------------------------------------------
# wxc: only initialized if not --with-msc
#--------------------------------------------------------------------
if test "$withmsc" != "yes"; then
  # we need wx-config
  if findprogram "$wxconfig"; then
    echo " wx-config found"
  else
    echo "error:"
    echo " Unable to find the 'wx-config' program: $wxconfig"
    echo " Maybe you forgot to run 'make install' on wxWidgets?"
    echo " Otherwise, add the install directory of wx-config to your path."
    if test "$WINDIR"; then
      echo ""
      echo " Or maybe you are trying to compile with Microsoft Visual C++?"
      echo " If so, you can specify that on the command line:"
      echo " For example: ./configure --with-msc"
    fi
    echo ""
    exit 2
  fi

  # initialize options for wxc
  cxx="`$wxconfig --cxx`"
  wxwincxxflags="`$wxconfig --cxxflags`"

  wxlibswanted="std"
  if test "$withopengl" = "yes"; then
    wxlibswanted="$wxlibswanted gl"
  else
    # override wxUSE_GLCANVAS=1 in the wxWidgets setup.h
    # file so that we can compile without --with-opengl
    # even if our wxWidgets supports it
    wxwincxxflags="-DwxcREFUSE_OPENGL $wxwincxxflags"
  fi

  if test "$withmediactrl" = "yes"; then
    wxlibswanted="$wxlibswanted media"
  else
    wxwincxxflags="-DwxcREFUSE_MEDIACTRL $wxwincxxflags"
  fi

  if test "$withcontrib" = "yes"; then
    wxlibswanted="$wxlibswanted stc svg"
    wxccontrib="-DwxUSE_STC=1 -DwxUSE_SVG=1"
  fi
  wxwinlibs="`$wxconfig --libs $wxlibswanted`"

  # version
  wxversion="`$wxconfig --version`"
  
  # extract the wxWidgets wxtoolkit: msw, mac, gtk etc.
  if test -z "$wxtoolkit"; then
    wxtoolkit="`$wxconfig --cxxflags | sed -e 's|.*-D__WX\([A-Z]*\)__.*|\1|'`"
  fi
  # to lowercase
  wxtoolkit="`echo "$wxtoolkit" | sed -e 'y|ABCDEFGHIJKLMNOPQRSTUVWXYZ|abcdefghijklmnopqrstuvwxyz|'`"

  # windows: 
  #  we append $prefix/include to the include directories
  #  we add "-lodbc32" since we use "SQL..." calls in the wrapper code :-(
  if test "$wxtoolkit" = "msw"; then
    wxwincxxflags="-I$prefix/include $wxwincxxflags"
    wxwinlibs="$wxwinlibs -lodbc32"
  fi

  # windows: we normalize $prefix and $exec-prefix include directories and libraries
  if test "$cygpathfound"; then
    wxprefix="`$wxconfig --prefix`"
    wxexecprefix="`$wxconfig --exec-prefix`"
    wwxprefix="`cygpath -w $wxprefix | sed -e 's|\\\\|/|g'`"
    wwxexecprefix="`cygpath -w $wxexecprefix | sed -e 's|\\\\|/|g'`"

    wxwincxxflags="`echo $wxwincxxflags | sed -e \"s|$wxprefix|$wwxprefix|g\"`"
    wxwinlibs="`echo $wxwinlibs | sed -e \"s|$wxexecprefix|$wwxexecprefix|g\"`"
  fi
  
  # macosx: we get the resource compiler flags
  wxrezcomp="`$wxconfig --rezflags`"
  wxrezfile=""
  if test "$wxrezcomp"; then
    for word in $wxrezcomp; do
      temp="`echo $word | grep '[^_]*_mac-[^r]*r'`"
      if test "$temp"; then
        wxrezfile="$temp"
      fi
    done
  fi
fi

if test "$wxrezfile"; then
  wxrezdir="`echo $wxrezfile | sed -e 's|\(.*\)/libwx_mac.*|\1|'`"
  wxinstallrezcomp="`echo \"${wxrezcomp}\" | sed -e \"s|${wxrezdir}|${libdir}|g\"`"
  wxinstallrezfile="`echo \"${wxrezfile}\" | sed -e \"s|${wxrezdir}|${libdir}|g\"`"
fi

#--------------------------------------------------------------------
# haskell compiler and package manager
#--------------------------------------------------------------------

# Do we have ghc?
if findprogram "$hc"; then
  echo " $hc found"
else
  echo "error:"
  echo " Unable to find: $hc"
  echo " Pleasy specify the path to GHC."
  echo " For example: ./configure --hc=/c/ghc/ghc-6.0/bin/ghc"
  exit 2
fi

# save haskell compiler name (as $hc also gets flags)
hcname="$hc"
ghcold="no"

if findprogram "basename"; then
  hcbasename="`basename $hcname | sed -e 's|-[0-9].*||' -e 's|\..*||'`"
else
  hcbasename="`echo $hcname | sed -e 's|-[0-9].*||' -e 's|\..*||'`"
fi


# check ghc version
hcversion="`$hc --version | sed -e 's|[A-Za-z \t,]*||'`"
if test "$hcbasename" = "ghc"; then
  case "$hcversion" in
    0* | 1* |  2* |  3* |  4* |  5.*)
	echo "WARNING:"
	echo " You seem to have an older ghc installed, namely $hcversion"
	echo " Ghc versions prior to 6.0 have garbage collector bugs that make wxHaskell"
	echo " applications *crash* and may contain incompatible libraries."
	echo " It is strongly advised to upgrade to a newer version."
	echo ""
	ghcold="yes";;
    6.0* | 6.1.* | 6.2* | 6.3* | 6.4* )
	echo "WARNING:"
	echo " You seem to have an older ghc installed, namely $hcversion"
        echo " Support for GHC version prior to 6.4 has been removed for simplicity."
        echo " It is strongly advised to upgrade to a newer version."
	ghcold="yes";;
    6.5* | 6.6* | 6.7* | 6.8* )
	ghcold="yes";;
    6.*) ;;
    7.*) ;;
    8.*) ;;
    9.*) ;;
    *)  echo "warning:"
	echo " Unable to recognise the ghc version ($hcversion ?)"
	echo " Be careful: ghc versions prior to 6.0 have bugs that make wxHaskell"
	echo " applications *crash* and may contain incompatible libraries."
	echo "";;
  esac
fi

# Do we have ghc-pkg?
if findprogram "$hcpkg"; then
  echo " $hcpkg found"
else
  echo "error:"
  echo " Unable to find: $hcpkg"
  echo " Pleasy specify the path to ghc-pkg."
  echo " For example: ./configure --hcpkg=/c/ghc/ghc-6.2/bin/ghc-pkg"
  hcpkg=echo
  exit 2
fi

# save name (hcpkg also gets flags)
hcpkgname="$hcpkg"	

if findprogram "basename"; then
  hcpkgbasename="`basename $hcpkgname | sed -e 's|-[0-9].*||' -e 's|\..*||'`"
else
  hcpkgbasename="`echo $hcpkgname | sed -e 's|-[0-9].*||' -e 's|\..*||'`"
fi


# Add local package flags
if test "$hcpkglocal"; then
  hc="$hc -package-conf $hcpkglocal"
  hcpkg="$hcpkg -f $hcpkglocal"
fi

# Get package's version
basepkgversion=`ghc-pkg latest base`
haskell98pkgversion=`ghc-pkg latest haskell98`

# Test if we can include the bytestring package explicitly
$hcpkg describe bytestring > /dev/null 2> /dev/null
case $? in
  0) bytestringpkgversion=`ghc-pkg latest bytestring`
     pkgbytestring="-package $bytestringpkgversion";;
  *) pkgbytestring="";;
esac

# Test if we can include the containers package explicitly
$hcpkg describe containers > /dev/null 2> /dev/null
case $? in
  0) containerspkgversion=`ghc-pkg latest containers`
     pkgcontainers="-package $containerspkgversion";;
  *) pkgcontainers="";;
esac

# Test if we can include the parsec package explicitly
$hcpkg describe parsec > /dev/null 2> /dev/null
case $? in
  0) pkgversion=`ghc-pkg latest parsec`
     pkgparsec="-package $pkgversion";;
  *) pkgparsec="";;
esac

# Test if we can include the time package explicitly
$hcpkg describe time > /dev/null 2> /dev/null
case $? in
  0) pkgversion=`ghc-pkg latest time`
     pkgtime="-package $pkgversion";;
  *) pkgtime="";;
esac

# Test if we can include the stm package explicitly
$hcpkg describe stm > /dev/null 2> /dev/null
case $? in
  0) stmpkgversion=`ghc-pkg latest stm`
     pkgstm="-package $stmpkgversion";;
  *) pkgstm="";;
esac

#--------------------------------------------------------------------
# Haddock
#--------------------------------------------------------------------
# Do we have haddock?
if findprogram "$hdoc"; then
  echo " $hdoc found"
  hdocfound="yes"
elif findprogram "haddock-ghc"; then
  hdoc="haddock-ghc"
  echo " $hdoc found"
  hdocfound="yes"
else
  echo "warning:"
  echo " Unable to find: $hdoc"
  echo " You won't be able to generate documentation."
  echo " You can specify the haddock executable on the command line."
  echo " For example: ./configure --haddock=/usr/local/bin/haddock"
  echo ""
  hdocbases=""
  hdocfound="no"
fi

# guess base.haddock location
if findprogram "ghc"; then
  guesshdocbase="`which ghc | sed -e 's|/bin/ghc|/doc/html/base/base.haddock|'`"
  # guesshdocbase="`which ghc | sed -e 's|/bin/ghc|/ghc-$hcversion/doc/ghc/libraries/base/base.haddock|'`"
  if test -f "$guesshdocbase"; then
    hdocbases="$guesshdocbase"
  fi
  if test "$cygpathfound"; then
    guessghclibdir=`which ghc | sed -e 's|/bin/ghc||'`
    normghclibdir="`cygpath -w $guessghclibdir | sed -e 's|\\\\|/|g'`"
  else
    guessghclibdir=`which ghc | sed -e "s|/bin/ghc|/lib/ghc-$hcversion|"`
    normghclibdir="$guessghclibdir"
  fi
  haddockversion=`$hdoc --version | sed -e "s|.*version \([0-9]*\)\..*|\1|"`
  if test -d "$normghclibdir" -a "$haddockversion" = "2"; then
    hdocbases="$hdocbases -B $normghclibdir"
  fi
fi


# Find .haddock files
if test "$hdocfound" = "yes"; then
  if findprogram "ghc"; then
    ghcroot="`which ghc | sed -e 's|/bin/ghc||'`"
    # set correct haddock root directory
    case "$hcversion" in
      6.0* | 6.1.* | 6.2* | 6.3* | 6.4* | 6.5* | 6.6*)
	docroot="$ghcroot/doc/html/libraries";;
      6.*) 
         if test "$cygpathfound"; then
           docroot="$ghcroot/doc/libraries"
         elif test -d "$ghcroot/share/doc/ghc/libraries"; then
           docroot="$ghcroot/share/doc/ghc/libraries"
         else
           docroot="$ghcroot/share/ghc-$hcversion/doc/ghc/libraries"
         fi
         ;;
      *)
	docroot="$ghcroot/doc/libraries";;
    esac
    # normalize the root since haddock doesn't like unix names
    if test "$cygpathfound"; then
      normdocroot="`cygpath -w $docroot | sed -e 's|\\\\|/|g'`"
    else
      normdocroot="$docroot"
    fi

    # modern ghc >= 6.2, include all available haddock files
    cd $docroot
    for file in */*.haddock
    do
      basename="`echo $file | sed -e 's|/.*||'`"
      hdocbases="$hdocbases -ihttp://www.haskell.org/ghc/docs/latest/html/libraries/$basename,$normdocroot/$file"
    done
    cd $topdir
  fi
fi

#--------------------------------------------------------------------
# wxWidgets
#--------------------------------------------------------------------

# confirm that we have unicode enabled

if test "$wxtoolkit" != "msw"; then
  `$wxconfig --unicode=yes`
  if test "$?" = 0; then
    echo " wxWidgets Unicode support found"
  else
    echo ""
    echo " I can't find the Unicode version of wxWidgets!"
    echo ""
    echo " Did you configure configure wxWidgets with --enable-unicode?"
    echo " If you have more than one copy, are you passing in the right"
    echo " version via --wx-config?"
    exit 1
  fi
fi

#--------------------------------------------------------------------
# install
#--------------------------------------------------------------------
if findprogram "install"; then
  echo " install program found"
  installdir="install -d"
  install="install -c"
else
  echo "warning:"
  echo " Unable to find 'install' (using 'cp' and 'mkdir' instead)."
  echo ""
  installdir="mkdir -p"
  install="cp -u"
fi

#--------------------------------------------------------------------
# strip and upx
#--------------------------------------------------------------------
if test "$enablestrip" = "yes"; then
 if findprogram "strip"; then
   echo " strip found"
 else
   echo "warning:"
   echo " Unable to find 'strip'. Libraries will not be stripped."
   echo ""
   enablestrip="no"
 fi
fi

if test "$enableupx" = "yes"; then
 if findprogram "upx"; then
   echo " upx found"
 else
   echo "warning:"
   echo " Unable to find 'upx'. Dynamic libraries will not be compressed."
   echo ""
   enableupx="no"
 fi
fi

if test "$enableupx" = "yes"; then
 if test "$enablestrip" = "yes"; then
   echo "warning:"
   echo " Using both 'strip' and 'upx' is not possible."
   echo " The libraries will not be stripped."
   echo ""
   enablestrip="no"
 fi
fi

runcompress=":"
if test "$enableupx" = "yes"; then
  runcompress="upx -qt \$(1) >/dev/null 2>/dev/null || if test \"\$?\" != \"0\"; then upx \$(1); fi"
else
 if test "$enablestrip" = "yes"; then
   runcompress="echo strip \$(1); strip \$(1)"
 fi
fi

if test "$enableoptimization" = "yes"; then
  hcflags="$hcflags -O$hcopt"
fi

if test "$enablesplitobjs" = "yes"; then
  hcflags="$hcflags -split-objs"
fi


#--------------------------------------------------------------------
# toolkit
#--------------------------------------------------------------------
if test -z "$wxtoolkit"; then
  echo "warning:"
  echo " Unable to determine the wxWindow toolkit."
  echo " Defaulting to 'msw'."
  echo ""
  wxtoolkit="msw"
fi

if test "$wxtoolkit" = "msw"; then
  bat=".bat"
else
  bat=""
fi

#--------------------------------------------------------------------
# Generate configuration
#--------------------------------------------------------------------

# Create directories
echo ""
echo "creating configuration files:"
echo " config"
mkdir -p config

# Finish generated files
if findprogram "date"; then
  date="`date`"
else
  date="<unknown>"
fi

if ! test "$bindir"; then
  bindir=$execprefix/bin
fi

#echo " makefile configuration"
echo " config/config.mk"
cat > config/config.mk << EOF
# Generated by configure on $date
TOPDIR=$topdir
VERSION=$version
RELEASE=$release
TOOLKIT=$wxtoolkit

# The Haskell compiler
HC=$hc
HCVERSION=$hcversion
HCNAME=$hcname
HCBASENAME=$hcbasename
HCFLAGS=$hcflags
HCPKG=$hcpkg
HCPKGOPT=$hcpkgopt
GHCOLD=$ghcold
ENABLE-PROF=$enableprof
ENABLE-SPLITOBJS=$enablesplitobjs
HC-PROF-FLAGS=-hisuf p_hi $hcprof

# Packages
PKG-BYTESTRING=$pkgbytestring
PKG-CONTAINERS=$pkgcontainers
PKG-PARSEC=$pkgparsec
PKG-TIME=$pkgtime
PKG-STM=$pkgstm

# C compiler
CXX=$cxx

# Installation
BINDIR=$bindir
LIBDIR=$libdir
SHARED-PREFIX=$sharedprefix
CONFIG-FLAGS=$configflags

# Compression function
run-compress=$runcompress

# Wxc
WITHMSC=$withmsc
WXC-LIBNAME=$wxclibname

# Contrib libraries
WXC-CONTRIB=$wxccontrib

# WxWidgets
WXWIN-VERSION=$wxversion
WXWIN-LIBS=$wxwinlibs
WXWIN-CXXFLAGS=$wxwincxxflags
WXWIN-REZFILE=$wxrezfile

# Platform
EXE=$exe
DLL=$dll
LIB=$lib
ARCHITECTURE=$architecture

# Documentation
HDOCFOUND=$hdocfound
HDOC=$hdoc
HDOCBASES=$hdocbases
USERNAME=$username

# Standard programs
INSTALL=$install
INSTALLDIR=$installdir
LD=ld
AR=ar
CP=cp -f
MV=mv
CD=cd
RM=rm -f
MKDIR=mkdir -p
RMDIR=rmdir
ZIP=zip
TAR=tar
GZIP=gzip
EOF

# put quotes around extra-ld-opts of non-empty
if test "$extraldopts"; then
  extraldopts="\"$extraldopts\""
fi

# create packages
binversion="${wxtoolkit}${wxversion}-${version}"

# behave like Cabal's configuration.
if test "$pkgcontainers"; then
  wxcoredepends="$basepkgversion, $containerspkgversion"
else
  wxcoredepends="$basepkgversion"
fi

#echo " package descriptions"
echo " config/wxcore.pkg"
# ghc 6.4+, the partial packages are only used for the windows installer
cat > config/wxcore-partial.pkg << EOF
name:wxcore
version:$version
license:LGPL
homepage:http://wxhaskell.sourceforge.net
author:Daan Leijen
maintainer:wxhaskell-devel@lists.sourceforge.net
exposed:True
exposed-modules: Graphics.UI.WXCore,
	Graphics.UI.WXCore.WxcClasses,
	Graphics.UI.WXCore.WxcClassInfo,
	Graphics.UI.WXCore.WxcDefs,
	Graphics.UI.WXCore.Types,
	Graphics.UI.WXCore.Defines,
	Graphics.UI.WXCore.DragAndDrop,
	Graphics.UI.WXCore.Draw,
	Graphics.UI.WXCore.Events,
	Graphics.UI.WXCore.Frame,
	Graphics.UI.WXCore.Layout,
	Graphics.UI.WXCore.Process,
	Graphics.UI.WXCore.Print,
	Graphics.UI.WXCore.Dialogs,
	Graphics.UI.WXCore.Image,
	Graphics.UI.WXCore.Controls,
	Graphics.UI.WXCore.Db,
	Graphics.UI.WXCore.OpenGL,
	Graphics.UI.WXCore.WxcObject,
	Graphics.UI.WXCore.WxcClassTypes,
	Graphics.UI.WXCore.WxcTypes,
	Graphics.UI.WXCore.WxcClassesAL,
	Graphics.UI.WXCore.WxcClassesMZ
hs-libraries:wxcore,wxcore0,wxcore1,wxcore2
extra-libraries:${wxclibname}-${binversion}
depends: ${wxcoredepends}, $haskell98pkgversion, $bytestringpkgversion, $stmpkgversion
extra-ld-opts:$extraldopts
EOF
tr -d \\r < config/wxcore-partial.pkg > config/wxcore.pkg
cp -f config/wxcore.pkg config/wxcore-partial.pkg
echo "import-dirs:\${wxhlibdir}/imports" >> config/wxcore.pkg
echo "library-dirs:\${wxhlibdir}"	 >> config/wxcore.pkg


echo " config/wx.pkg"
cat > config/wx-partial.pkg << EOF
name:wx
version:$version
license:LGPL
homepage:http://wxhaskell.sourceforge.net
author:Daan Leijen
maintainer:wxhaskell-devel@lists.sourceforge.net
exposed:True
exposed-modules: Graphics.UI.WX,
	Graphics.UI.WX.Types,
	Graphics.UI.WX.Attributes,
	Graphics.UI.WX.Layout,
	Graphics.UI.WX.Classes,
	Graphics.UI.WX.Variable,
	Graphics.UI.WX.Events,
	Graphics.UI.WX.Window,
	Graphics.UI.WX.TopLevelWindow,
	Graphics.UI.WX.Frame,
	Graphics.UI.WX.Media,
	Graphics.UI.WX.Menu,
	Graphics.UI.WX.Timer,
	Graphics.UI.WX.Draw,
	Graphics.UI.WX.Controls,
	Graphics.UI.WX.Dialogs
hs-libraries:wx
depends: wxcore-${version}, $stmpkgversion
EOF
tr -d \\r < config/wx-partial.pkg > config/wx.pkg
cp -f config/wx.pkg config/wx-partial.pkg
echo "import-dirs:\${wxhlibdir}/imports" >> config/wx.pkg
echo "library-dirs:\${wxhlibdir}"	 >> config/wx.pkg


# set version in msc project file
updateversion () {
  sed -e "s|wxc-msw[\\.0-9]\+-[\\.0-9]\+\\.|wxc-${binversion}.|g" -e "s|wxcd-msw[\\.0-9]\+-[\\.0-9]\+\\.|wxcd-${binversion}.|g" -e "s|\$|\\r|g" $1 > $1.out
  mv -f $1.out $1
}

if test "$withmsc" = "yes"; then
  echo " update version number in visual c++ project file"
  for dsp in wxc/*.dsp
  do
    updateversion $dsp
  done
fi

# create installer scripts
# echo " installer scripts"

# generate windows installer files.
echo " config/wxhaskell-register.bat"
echo "@SET wxclibname=${wxclibname}-${binversion}"	>  config/wxhaskell-register-temp
echo "@SET generate=yes" >> config/wxhaskell-register-temp
cat config/wxhaskell-register-temp bin/wxhaskell-register-template.bat | sed -e "s|\${hcregister}|ghc-pkg update|g" -e "s|\$|\\r|g" > config/wxhaskell-register.bat
rm -f config/wxhaskell-register-temp

echo " config/wxhaskell-unregister.bat"
echo "@SET wxclibname=${wxclibname}-${binversion}"	>  config/wxhaskell-unregister-temp
cat config/wxhaskell-unregister-temp bin/wxhaskell-unregister-template.bat | sed -e "s|\${hcunregister}|ghc-pkg unregister|g" -e "s|\$|\\r|g" > config/wxhaskell-unregister.bat
rm -f config/wxhaskell-unregister-temp

echo " config/setcd"
cp bin/setcd config/setcd

cat > config/README-template-windows << EOF
Click on the newly created wxhaskell-${version}\\bin\\wxhaskell-register.bat
program to register the wxHaskell package.

To uninstall, you can click on
wxhaskell-${version}\\bin\\wxhaskell-unregister.bat and than remove the
wxhaskell-${version} directory.
EOF

if test "$wxtoolkit" = "msw"; then
  cat config/README-template-windows | sed -e "s|\${version}|${version}|g" > README.txt
fi

# generate maxosx installer files.
echo " config/macosx-install.info"
cat > config/macosx-install.info << EOF
Title wxHaskell
Version $version
Description wxHaskell library
DefaultLocation $prefix
DeleteWarning
NeedsAuthorization YES
Required NO
Relocatable NO
RequiresReboot NO
UseUserMask YES
OverwritePermissions NO
InstallFat NO
RootVolumeOnly YES
EOF

# generate macosx post-install files.
echo " config/macosx-postinstall"
cat > config/macosx-postinstall << EOF
#!/bin/sh

GHCPKG=`which ghc-pkg`
# try these versions of GHC-PKG in turn
# would it maybe be best just to let the installer fail?
if test "\$GHCPKG" = ""; then
  if test -f /usr/local/bin/ghc-pkg; then
    GHCPKG=/usr/local/bin/ghc-pkg
  elif test -f /opt/local/bin/ghc-pkg; then
    GHCPKG=/opt/local/bin/ghc-pkg
  elif test -f /sw/bin/ghc-pkg; then
    GHCPKG=/sw/bin/ghc-pkg
  else
    echo "I can't find ghc-pkg in the path (\$PATH)!"
    echo "Is GHC even installed?"
    exit 1
  fi
fi
cat "\$1/Contents/Resources/wxcore.pkg" | sed -e "s|\\\${wxhlibdir}|${libdir}|" | \$GHCPKG --global update -
cat "\$1/Contents/Resources/wx.pkg" | sed -e "s|\\\${wxhlibdir}|${libdir}|" | \$GHCPKG --global update -
EOF

chmod a+x config/macosx-postinstall

# generate macosx application builder script
echo " config/macosx-app"
cat > config/macosx-app-temp << EOF
#!/bin/sh
rezcomp="$wxinstallrezcomp"
rezfile="$wxinstallrezfile"

EOF
cat config/macosx-app-temp bin/macosx-app-template > config/macosx-app
rm -f config/macosx-app-temp
chmod a+x config/macosx-app

# generate RPM spec file

# to uppercase
wxToolkit="`echo "$wxtoolkit" | sed -e 'y|abcdefghijklmnopqrstuvwxyz|ABCDEFGHIJKLMNOPQRSTUVWXYZ|'`"

echo " config/wxhaskell.spec"
echo "%define wxhversion   $version"	>  config/wxhaskell.spec.temp
echo "%define wxhrelease   $release"	>> config/wxhaskell.spec.temp
echo "%define hcomp        $hcbasename"		>> config/wxhaskell.spec.temp
echo "%define hcpkg        $hcpkgbasename"	>> config/wxhaskell.spec.temp
echo "%define hcversion    $hcversion"		>> config/wxhaskell.spec.temp	
echo "%define wxtoolkit    $wxtoolkit"		>> config/wxhaskell.spec.temp
echo "%define wxToolkit    $wxToolkit"		>> config/wxhaskell.spec.temp
echo "%define wxversion    $wxversion"		>> config/wxhaskell.spec.temp
echo "%define sourceroot   $topdir/dist/"       >> config/wxhaskell.spec.temp
echo "%define configflags  $arguments_exp"	>> config/wxhaskell.spec.temp
echo ""						>> config/wxhaskell.spec.temp
cat config/wxhaskell.spec.temp bin/wxhaskell-spec-template > config/wxhaskell.spec
rm -f config/wxhaskell.spec.temp

# generate prologue for documentation
echo " config/prologue.txt"
echo "Documentation for wxHaskell $version"  >  config/prologue.txt.temp
echo ""                                      >> config/prologue.txt.temp
cat config/prologue.txt.temp bin/prologue-template.txt > config/prologue.txt
rm -f config/prologue.txt.temp

# save arguments
echo " config/cache.txt"
echo "$arguments_exp" > config/cache.txt

# show configuration
echo ""
echo "configuration:"
echo " library:     wxhaskell-$version  (release $release)"
echo " compiler:    $hcbasename-$hcversion"
echo " wxwidgets:   $wxtoolkit-$wxversion"
echo " extensions:"
echo "   openGL:    $withopengl"
echo "   mediactrl: $withmediactrl"
echo "   contrib:   $withcontrib"
echo " library dir: $libdir"

if test "$wxrezfile"; then
echo " resource:    $wxrezfile"
fi  

# we are done.
echo ""
echo "done:"
echo " type 'make' to build wxhaskell."
echo " type 'make install' to install wxhaskell."
echo " type 'make help' to receive help on all other make targets"
echo ""
