#!/bin/bash

if [ -z "${JAVA_HOME}" ]; then
	echo ""
	echo "ERROR JAVA_HOME environment variable must be defined and point to an HJ Distribution"
	echo ""
    exit 1
fi


if [ -z "${HJ_HOME}" ]; then
	echo ""
	echo "ERROR HJ_HOME environment variable must be defined and point to an HJ Distribution"
	echo ""
    exit 1
fi

UNAME=`uname -s -p | sed -e 's/ /,/g'`
FILE_SEP='/'; if [[ "$UNAME" = CYGWIN* ]]; then FILE_SEP='\'; fi
PATH_SEP=':'; if [[ "$UNAME" = CYGWIN* ]]; then PATH_SEP=';'; fi
[ -n "$HJ_PLATFORM" ] || \
case "$UNAME" in
  CYGWIN*) HJ_PLATFORM='win32_x86';;
  Linux,*) HJ_PLATFORM='linux_x86';;
  AIX,*) HJ_PLATFORM='aix_ppc';;
  Darwin,i386) HJ_PLATFORM='macosx_x86';;
  Darwin,powerpc) HJ_PLATFORM='macosx_ppc';;
  SunOS,sparc) HJ_PLATFORM='sunos';;
  *) echo "Unrecognized platform: '$UNAME'"; exit 1;;
esac
# FIXME: the above assumes that Cygwin==win32 and Linux==x86 and AIX==ppc

TOP="$(cd "$(dirname $0)/.." && pwd)"
if [[ "$UNAME" = CYGWIN* ]]; then TOP="$(cygpath -aw "$TOP")"; fi

if [ -n "$JAVA_HOME" -a -e "$JAVA_HOME/bin/java" ]; then
    JAVA="$JAVA_HOME/bin/java"
elif [ -n "$JRE_HOME" -a -e "$JRE_HOME/bin/java" ]; then
    JAVA="$JRE_HOME/bin/java"
else
    echo "JAVA_HOME ($JAVA_HOME) is not pointing to a JRE or a JDK"
    exit 1
fi
if [[ "$UNAME" = CYGWIN* ]]; then JAVA="$(cygpath -au "$JAVA")"; fi
if [[ "$UNAME" = CYGWIN* ]]; then JAVA_HOME="$(cygpath -aw "$JAVA_HOME")"; fi

help=""
time=""
verbose=""
version=""
extra_cp=""
extra_lib=""
mx=""
places_opt=""
nb_places=
nb_thread_per_place=
defs=""
dev=""
java_args=""
args=""

parse=true
while [ -n "$1" ]; do
    if [ -z "$parse" ]; then
        args="$args '$1'"
        shift
        continue
    fi
    case "$1" in
        -h|-help|--help) help="1"; break;;
        -verbose|--verbose) verbose="1";;
        -t|-time) time="time ";;
        -places) shift; places_opt="$1";;
        -mx) shift; mx="$1";;
        -D*) if [[ "${1##-D}" = java.library.path=* ]]; then
                 echo >&2 "Error: Cannot reset java.library.path, use -libpath instead"
                 exit 1
             fi
             # TODO: add tests for more system properties above
             defs="${defs} $1";;
        -classpath|-cp) shift; extra_cp="$1";;
        -libpath) shift; extra_lib="$1";;
        -config) shift; config="$1.cfg";;
        -dev) dev="true";;
        -J*) java_args="${java_args} '${1##-J}'";;
        --) parse=;;
        *) args="$args '$1'";;
    esac
    shift
done

if [ -n "$help" -o -z "$args" ]; then
    cat << EOF
Usage: hj [options] <main-class> [arg0 arg1 ...]
where [options] includes:
    -t -time                 display execution time
    -v -verbose --verbose    print verbose debugging information
    -version --version 	   	 print version number of the hj runtime
    -h -help --help          print this message
    -mx <size>               set max heap size, e.g., -mx 200M
    -places <p>:<t>          set number of places and threads per places
    -D<name>=<value>         set system property <name> to <value>
    -classpath <path>        search path for class files
    -libpath <path>          search path for native libraries
    -config <conf>           read configuration <conf> from etc${FILE_SEP}<conf>.cfg
    -dev                     developer mode (use unpackaged Hj libraries)
    -J<arg>                  [USE WITH CAUTION] pass <arg> directly to java.
        e.g., use -J-verbose to make java execution verbose.
        
    Note: every other - prepend options will be passed to the hj runtime (syntax is -optname=optvalue)
    Use "hj -- -help" to get help on Hj runtime configuration options
EOF
    exit 1
fi


#CONFIG_DIR="${TOP}${FILE_SEP}etc"

#[ -n "$config" ] && config="-Dhj.configuration=\"${CONFIG_DIR}${FILE_SEP}${config}\""

classpath=""

for file in `ls ${HJ_HOME}/lib`; do
	classpath=${classpath}:${HJ_HOME}/lib/$file
done

if [ -n "$extra_cp" ]; then
   classpath="$extra_cp${PATH_SEP}$classpath"
fi

externpath="${TOP}${FILE_SEP}lib${FILE_SEP}${HJ_PLATFORM}"
if [ -n "$extra_lib" ]; then
   externpath="$extra_lib${PATH_SEP}$externpath"
fi

java_args="-Djava.library.path=\"$externpath\" -ea -classpath \"$classpath\" ${java_args}"


###############################
# Handle HJ WSH Runtime Options
###############################
	
#Handle nb place and nb thread per place
if [ -n "$places_opt" ]; then

	nb_places=`echo $places_opt | cut -d':' -f1-1`
	nb_thread_per_place=`echo $places_opt | cut -d':' -f2-2`

	#We add one thread, for the main activity that will remain blocked (check HJ-147 for comments)
	nb_thread_per_place=`expr $nb_thread_per_place \+ 1`

	# if these options are specified in addition to -place they override the following.
	args="-INIT_THREADS_PER_PLACE=${nb_thread_per_place} -NUMBER_OF_LOCAL_PLACES=${nb_places} ${args}"

fi

#####################
# Handle Java Options
#####################

if [ -n "$mx" ]; then
   java_args="-Xmx$mx $java_args"
fi
java_args="${java_args} ${defs}"

##############################
# Build the final command line
##############################

command="\"$JAVA\" $java_args $config hj.lang.Runtime $args"	

[ -n "$verbose" ] && echo "$command"

eval "$time$command"
exit $?
