#! /bin/sh
# this script jumps in if there is no working mcc on the path:
# - on Mac OS it (hopefully) figures out the location of mcc,
# - on Cygwin it substitutes mcc completely
# this file is part of FeynHiggs
# last modified 29 Jun 07 th


sdkpath()
{
  mathcmd="$1"
  shift

  for dir in "$@" ; do
    path="$dir:$path"
  done
  
  sdk=`PATH="$PATH:$path" "$mathcmd" << \_EOF_ | tail -1
	WriteString["stdout", "\n" <>
	  ToFileName[{$TopDirectory, "AddOns", "MathLink",
	    "DeveloperKit", $SystemID, "CompilerAdditions"}]]; Exit[]
_EOF_`
  [ -z "$sdk" ] || return

  echo "Cannot determine system type" 1>&2
  exit 1
}


cygmcc()
{
  sdkpath math "$PROGRAMFILES/Wolfram Research/Mathematica"/*
  for sdk in "$sdk"/* ; do
    break
  done

  cache=MLcyg-cache
  [ -d $cache ] || mkdir $cache

  OSbits=32
  MLversion=1

  dllname=ml${OSbits}i$MLversion
  libname="$sdk/lib/${dllname}m.lib"
  lib="$cache/${dllname}m"
  [ -f "$lib.a" ] || {
    ( echo "EXPORTS"
      nm -C --defined-only "$libname" | awk '/ T [^.]/ { print $3 }' ) > "$lib.def"
    dlltool --dllname "$dllname.dll" --def "$lib.def" --output-lib "$lib.a" -k
  }

  for arg in "$@" ; do
    case "$arg" in
    -l* | -L* | *.a)
	ldflags="$ldflags $arg" ;;
    *.tm)
	cp "$arg" "$arg.tm"
	"$sdk"/bin/mprep -lines -o "$arg.c" "$arg.tm"
	tmp="$tmp $arg.c $arg.tm"
	ccflags="$ccflags $arg.c" ;;
    *)
	ccflags="$ccflags $arg" ;;
    esac
  done

  trap "rm -f $tmp" 0 1 2 3 15

  set -x
  ${CC:-gcc} -DWIN$OSbits -I"$sdk/include" $ccflags $ldflags $lib.a -mwindows
}


macmcc()
{
  sdkpath MathKernel /Applications/Mathematica*/Contents/MacOS \
                     $HOME/Desktop/Mathematica*/Contents/MacOS

  "$sdk/mcc" "$@" && exit 0

  echo "mcc not found"
}



shopt -s nullglob 2> /dev/null

ostype=`uname -s`

case $ostype in
Darwin) macmcc "$@" ;;
CYG*)   cygmcc "$@" ;;
*)      echo "Unknown OS $ostype" 1>&2 ;;
esac

