#!/bin/bash

BOOTCLASSPATH=""
CLASSPATH=""

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

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

#

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

IDE_PLUGIN_PATH="$DEVICE_PATH/../../../ide/plugins/*"
MAC_IDE_PLUGIN_PATH="$DEVICE_PATH/../../../TizenStudio.app/Contents/Eclipse/plugins/*"
DEVICE_PATH_JAR="$DEVICE_PATH/$DEVICE_JAR"


# 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

CLASSPATH="$DEVICE_PATH_JAR:$IDE_PLUGIN_PATH:$MAC_IDE_PLUGIN_PATH:$CLASSPATH"

# Add support for OpenJDK
# JAVAFx lib should be present downloaded and placed in JAVA installation lib folder from JAVA 11.

OLDIFS=$IFS
version=$("$JAVA" -version 2>&1 | awk -F '"' '/version/ {print $2}')
IFS='.' tokens=( $version )
majorVer=${tokens[0]}
IFS=$OLDIFS
JRE_OPT=""
if [ $majorVer -ge 9 ]; then
  if [[ $(java -version 2>&1) == *"OpenJDK"* ]];then
    JRE_OPT="--module-path $JRE_HOME/lib/javafx.graphics.jar:$JRE_HOME/lib/javafx.controls.jar:$JRE_HOME/lib/javafx.fxml.jar:$JRE_HOME/lib/javafx.base.jar --add-exports=javafx.graphics/com.sun.javafx.tk=ALL-UNNAMED --add-modules=javafx.controls --add-modules=javafx.fxml "
  fi
fi


# run
if [ -z "$IN_APP" ]
then
    $JAVA $JRE_OPT -Xbootclasspath/a:"$BOOTCLASSPATH" -cp "$CLASSPATH":. org.tizen.device.manager.Main "$@"
else
    $JAVA $JRE_OPT -Xbootclasspath/a:"$BOOTCLASSPATH" -cp "$CLASSPATH":. org.tizen.device.manager.Main
fi
