#! /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
# last modified 2 Feb 11 th


sdkpath()
{
  mathcmd="$1"
  shift
  mathcmd=`IFS=:
    PATH="$PATH:$*" which $mathcmd`
  
  eval `"$mathcmd" -run '
    Print["sysid=\"", $SystemID, "\""];
    Print["topdir=\"", $TopDirectory, "\""];
    Exit[]' < /dev/null | tr '\r' ' ' | tail -2`

	# Cygwin's dlltool does not handle native 64-bit libraries yet
  [ "$sysid" = Windows-x86-64 ] && sysid=Windows
  topdir=`cd "$topdir" ; echo $PWD`

  for sdk in \
    "$topdir/AddOns/MathLink/DeveloperKit/$sysid/CompilerAdditions" \
    "$topdir/SystemFiles/Links/MathLink/DeveloperKit/$sysid/CompilerAdditions" \
    "$topdir/SystemFiles/Links/MathLink/DeveloperKit/CompilerAdditions" ; do
    [ -d "$sdk" ] && return
  done

  echo "Cannot determine Mathematica's system ID using $mathcmd" 1>&2
  exit 1
}


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

  [ `basename "$sdk"` = cygwin ] && {
    CC=${CC:-gcc} bash -O igncr "$sdk/bin/mcc" "$@"
    return
  }

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

  MLversion=3
  for OSbits in 32 64 ; do
    dllname=ml${OSbits}i$MLversion
    libname="$sdk/lib/${dllname}m.lib"
    [ -f "$libname" ] && break
  done

  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

