#!/usr/bin/env bash

# stop script when a command returns with non-zero
set -e

POCAML=""
PFLAGS=""
COMPILE_ONLY=false
FROM_STDIN=false
LOCAL=false

Usage()
{
  echo
  echo "usage:	pocaml [options] [<path_to_pml_file>...]"
  echo
  echo "-c	Only compile .pml files"
  echo "-h	Display this help"
  echo

  exit 1
}

SetFlags()
{
    if [ "$COMPILE_ONLY" = "false" ]
    then
	PFLAGS="$PFLAGS -r"
    fi

    if [ "$FROM_STDIN" = "false" ]
    then
	PFLAGS="$PFLAGS -f"
    fi
}

SetCommand()
{
    if [ "$LOCAL" = true ]
    then
	POCAML="./pocamlc"
    else
	POCAML="./runDocker ./pocamlc"
    fi
}

[ $# -eq 0 ] && Usage

while getopts chl opt; do
    case $opt in
	c)
	    COMPILE_ONLY=true
	    ;;
	l)
	    LOCAL=true
	    ;;
	*)
	    Usage
	    ;;
    esac
done

shift $(($OPTIND - 1))

if [ $# -eq 0 ]
then
    FROM_STDIN=true
fi

SetFlags
SetCommand

for file in $@
do
    $POCAML $PFLAGS $file
done

if [ $FROM_STDIN = true ]
then
    $POCAML $PFLAGS
fi

exit 0
