#!/bin/sh
# SeokYeon Hwang <syeon.hwang@samsung.com>

BOOTCLASSPATH=""
CLASSPATH=""

# find directory of script file
SCRIPT_DIR="$(cd "$(dirname "$0")" ; pwd -P)"

# find current directory
CURRENT_DIR="$(pwd -P)"

# find emulator manager binary in current dir first
EM_JAR="em-ui-3.0.jar"
if [ -f "$CURRENT_DIR/$EM_JAR" ]
then
    EM_PATH="$CURRENT_DIR/$EM_JAR"
elif [ -f "$SCRIPT_DIR/$EM_JAR" ]
then
    EM_PATH="$SCRIPT_DIR/$EM_JAR"
elif [ -f "$SCRIPT_DIR/../../../$EM_JAR" ]
then
    # we are in app directory
    EM_PATH="$SCRIPT_DIR/../../../$EM_JAR"
    IN_APP="yes"
else
    echo "Can not find $EM_JAR"
    exit
fi


# find JRE_HOME
UNAME=$(uname)
case "$UNAME" in
Linux)
    JRE_HOME="$(dirname $(dirname $(readlink -f $(which java))))"
    ;;
Darwin)
    JAVA_DIR=$(dirname $(readlink $(which java)))
    if [ -f "$JAVA_DIR/java_home" ]
    then
        JRE_HOME=$($JAVA_DIR/java_home)
    else
        JRE_HOME="$(readlink $JAVA_DIR)"/../
    fi
    ;;
MINGW*)
    echo "Please execute \"emulator-manager.exe\""
    exit
    ;;
esac

if [ -d "$JRE_HOME/jre" ]
then
        JRE_HOME="$JRE_HOME/jre"
fi

# find jfxrt.jar
JFXRT_JAR="jfxrt.jar"
JFXRT_PATH="$JRE_HOME/lib/ext/$JFXRT_JAR"
if [ -f "$JFXRT_PATH" ]
then
    # java 8 or above
    # we have nothing to do
    :
else
    JFXRT_PATH="$JRE_HOME/lib/$JFXRT_JAR"
    if [ -f "$JFXRT_PATH" ]
    then
        # java 7u6 or above
        # use JRE providing one
        BOOTCLASSPATH="$BOOTCLASSPATH:$JFXRT_PATH"
    else
        # java 7u5 or below
        # try to run with our own
        JFXRT_PATH="$SCRIPT_DIR/$JFXRT_JAR"
        if [ -f "$JFXRT_PATH" ]
        then
            CLASSPATH="$CLASSPATH:$JFXRT_PATH"
        fi
    fi
fi

if [ -f "$JRE_HOME/bin/java" ]
then
    JAVA=$JRE_HOME/bin/java
else
    JAVA=java
fi

# run
if [ -z "$IN_APP" ]
then
    $JAVA -Xbootclasspath/a:"$BOOTCLASSPATH" -cp "$CLASSPATH" -jar "$EM_PATH" "$@"
else
    $JAVA -Xbootclasspath/a:"$BOOTCLASSPATH" -cp "$CLASSPATH" -jar "$EM_PATH"
fi
