#!/bin/sh

# Fix FLEXLINKFLAGS
if test -n "VS90COMNTOOLS"; then
  echo Toolchain msvc 2008, fixing FLEXLINKFLAGS
  export FLEXLINKFLAGS="-real-manifest"
fi

# Removing previously accessible ocaml in PATH
echo Removing previously accessible ocaml binary from PATH
CONF=
while which ocaml > /dev/null 2>&1; do
  PATH_TO_REMOVE=$(dirname "$(which ocaml)")
  CONF=$(dirname "$PATH_TO_REMOVE")
  echo CONF $CONF
  echo Removing $PATH_TO_REMOVE
  case $PATH_TO_REMOVE in
    /cygdrive/*)
    OLD_IFS=$IFS
    IFS=":"
    REMOVED=false
    NEW_PATH=""
    for i in $PATH; do
      if ! [ "$i" = "$PATH_TO_REMOVE" ]; then
        NEW_PATH="$NEW_PATH:$i"
      else
        REMOVED=true
      fi
    done
    IFS=$OLD_IFS
    if ! $REMOVED; then
      echo Cannot find path to remove >&2
      exit 1
    fi
    PATH=$NEW_PATH
    ;;
    *)
    echo Cannot remove path $PATH_TO_REMOVE, only path under /cygdrive/ can be removed >&2
    exit 1
    ;;
  esac
done

# Overriding link in PATH
LINK_PATH=$(which -a link | grep "^/cygdrive/" | (read i; dirname "$i"))
PATH="$LINK_PATH:$PATH"
echo Setting path for link to $LINK_PATH:...

# Setting $LIB
LIB="$LIB;C:\\Program Files\\Microsoft Platform SDK\\Lib"

# Setting $INCLUDE
INCLUDE="$INCLUDE;C:\\Program Files\\Microsoft Platform SDK\\Include"

# Unset OCAMLLIB
unset OCAMLLIB

# Fix link
LINKDIR=$(dirname "$(which -a link | grep "/cygdrive/")")
export PATH=$LINKDIR:$PATH
echo -n "link is now: "; which link
echo

ocaml_root ()
{
  root="$1"
  export PATH="$root/bin:$PATH"
  export OCAMLLIB="$(cygpath -w $root/lib)"
}

detect_ocaml ()
{
  for i in /cygdrive/*; do
    for j in $i/ocaml*; do
      if test -x $j/bin/ocaml; then
        CONF="$CONF $j"
      fi
    done
  done
}

detect_ocaml 

echo 0 - None

idx=1
for i in $CONF; do
  echo $idx "-" $i
  idx=$(($idx + 1))
done

echo -n "Which configuration for OCaml? "
read i 
if ! [ "$i" = "0" ]; then
  MY_CONF=$(echo $CONF | cut -f $i -d " ")
  ocaml_root $MY_CONF
fi

unset CONF
unset MY_CONF
