#!/bin/bash
#
# Small wrapper to deal with compilation of the compiler and the stdlib.

STATUS=0

RUN_DIR="`pwd`"

SCRIPT_DIR=`dirname $(realpath $0)`

COMPILER_DIR="$SCRIPT_DIR/compiler"
if [ -x $COMPILER_DIR/heptc.native ];
then
    COMPILER=heptc.native
else
    COMPILER=heptc.byte
fi
COMPILER_DEBUG=heptc.d.byte
LIB_DIR="$SCRIPT_DIR/lib"

JAVA_LIB_DIR="$LIB_DIR/java"
JAVAC="javac -Xlint:unchecked -cp $JAVA_LIB_DIR"

#the symlink
HEPTC="$COMPILER_DIR/$COMPILER"
HEPTC_DEBUG="$COMPILER_DIR/$COMPILER_DEBUG"

#compile the compiler
if [ ! -x "$HEPTC" ]
then
  if [ -x "$HEPTC_DEBUG" ]
  then
    #use the debug
    HEPTC=$HEPTC_DEBUG
  else
    pushd "$COMPILER_DIR" > /dev/null
    ocamlbuild -use-ocamlfind -j 0 "$COMPILER"
    popd > /dev/null
  fi
fi

#compile the stdlib
if [ ! -e "$LIB_DIR/pervasives.epci" ] || [ "$HEPTC" -nt "$LIB_DIR/pervasives.epci" ]
then
  pushd "$LIB_DIR" > /dev/null
  echo "Recompile pervasives.epci" > /dev/stderr
  "$HEPTC" -nopervasives pervasives.epi
  popd > /dev/null
fi

function compile
{
  #call the compiler with the passed arguments.
  pushd "$RUN_DIR" > /dev/null
  "$HEPTC" -stdlib "$LIB_DIR" "$@"
  STATUS=$?
  popd > /dev/null
}

case $1 in
java )
  shift
  compile -target java "$@"
  if [[ $STATUS = 0 ]]
  then
    #call javac to compile the file given as last argument
    last_arg=$#
    base_f=`basename ${!last_arg} .ept`
    pushd "java/$(echo ${base_f} | sed 's/^./\u&/')" > /dev/null
    ${JAVAC}:.. *.java
    popd > /dev/null
  fi
;;
c )
  shift
  set -e
  compile -target c "$@"
  base_f=`basename ${!#} .ept`
  cd ${base_f}_c && cc -I`$HEPTC -where`/c *.c -o ../${base_f}
;;
-- | * )
  compile "$@"
esac

exit $STATUS
