#!/bin/bash

#set -x

# You can set JAVA_HOME to point ot JDK 1.4, or shell will try to
# deterine java location using which

if [ -z "$JAVA_HOME" ] ; then
    JAVA=`/usr/bin/which java`
    if [ -z "$JAVA" ] ; then
        echo "Cannot find JAVA. Please set your PATH."
        exit 1
    fi
    JAVA_BIN=`dirname "$JAVA"`
    JAVA_HOME=$JAVA_BIN/..
else
    JAVA="$JAVA_HOME/bin/java"
fi

if [ ! "`"$JAVA" -version 2>&1 | grep "\ 1\.[456789]"`" ]; then
    echo Required 1.5 verion of JDK: can not use $JAVA
    echo Current version is:
    "$JAVA" -version
    exit 1
fi

# Get directory path.
PRG="$0"
while [ -h "$PRG" ] ; do
  ls=`ls -ld "$PRG"`
  link=`expr "$ls" : '.*-> \(.*\)$'`
  if expr "$link" : '.*/.*' > /dev/null; then
    PRG="$link"
  else
    PRG=`dirname "$PRG"`/"$link"
  fi
done
PRGDIR=`dirname "$PRG"`

CP=`/bin/sh $PRGDIR/classpath.sh run`

# Cygwin trick
cygwin=false
case "`uname`" in
  CYGWIN*) cygwin=true;
esac

if $cygwin; then
  CP=`cygpath --path --windows "$CP"`
  # JAVA=`cygpath --unix "$JAVA.exe"`
fi

JAVA_OPTS="-Dlog=edu.indiana.extreme.xbaya:ALL"
#JAVA_OPTS="-Dlog"
#JAVA_OPTS="-Xrunhprof:cpu=samples,depth=6,thread=y,file=java.hprof-$$.txt"

if [ $# -ge 1 ] ; then
  NAME=$1
  shift
else
  NAME=application
fi

if [ "$NAME" = "application" ] ; then
    NAME="edu.indiana.extreme.xbaya.XBaya -enableLocalRegistry"
elif [ "$NAME" = "xbaya" ] ; then
    NAME="edu.indiana.extreme.xbaya.XBaya -enableLocalRegistry"
elif [ "$NAME" = "allservices" ] ; then
    NAME="edu.indiana.extreme.xbaya.test.service.AllServices"
elif [ "$NAME" = "adder" ] ; then
    NAME="edu.indiana.extreme.xbaya.test.service.adder.AdderService"
    PORT="-port 10000"
elif [ "$NAME" = "multiplier" ] ; then
    NAME="edu.indiana.extreme.xbaya.test.service.multiplier.MultiplierService"
fi

OPTS="$JAVA_OPTS -cp $CP $NAME $* $PORT"
echo CMD=$JAVA $OPTS
"$JAVA" $OPTS
