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

getEmbeddedJDKPath() {
    DONE=false
    until $DONE; do
    read line || DONE=true
    
    # reading each line
    if [[ $line == TIZEN_SDK_INSTALLED_PATH* ]]; then 
        sdkPath="$(cut -d'=' -f2 <<<$line)";
    fi
    if [[ $line == TIZEN_SDK_DATA_PATH* ]]; then 
        sdkDataPath="$(cut -d'=' -f2 <<<$line)"
    fi
    if [[ $line == JDK_PATH* ]]; then 
        sdkInfoJDKPath="$(cut -d'=' -f2 <<<$line)"
    fi
    
    done < "$1"
}

createlogFile(){
    date_time=$(date +"%Y%m%d%H%M%S")
    fileName="em_$date_time.txt"
    if [ ! -d "${sdkDataPath}/emulator" ]; then
        mkdir -p "${sdkDataPath}/emulator"
    fi
    logFilePath="$sdkDataPath/emulator/$fileName"
    touch "$logFilePath"
    logFile="$logFilePath"
}

setJavaExecPath(){
    # extract the sdkPath, sdkDataPath, sdkInfoJDKPath
    getEmbeddedJDKPath $sdkInfoPath
    logMessage=""
    # update JAVA_EXEC if JDK_PATH specified(and exists) in sdk.info 
    if [ -d "$sdkInfoJDKPath" ]; then
        # jdk directory exixts
        JDK_PATH="$sdkInfoJDKPath"
        logMessage="${logMessage}Using Sdk.info java at ${JDK_PATH}"$'\n'
    elif [[ "$sdkInfoJDKPath" != "" ]]; then 
        logMessage="${logMessage}Jdk specified in sdk.info:${sdkInfoJDKPath} does not exist."$'\n'
    fi


    if [ ! -d "$JDK_PATH" ]; then 
        JAVA_EXEC="java"
        logMessage="${logMessage}Using System java"$'\n'
    else
        UNAME=$(uname)
        case "$UNAME" in
        Linux)
                JAVA_EXEC="$JDK_PATH/bin/java"
            ;;
        Darwin)
                JAVA_EXEC="$JDK_PATH/Contents/Home/bin/java"
            ;;
        esac
    fi

    if [[ ${logMessage} != ""  ]]; then 
        # make the log file
        createlogFile
        echo "${logMessage}">>${logFile}
    fi
}

# 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"
    EM_PATH_DIR="$CURRENT_DIR"
elif [ -f "$SCRIPT_DIR/$EM_JAR" ]
then
    EM_PATH="$SCRIPT_DIR/$EM_JAR"
    EM_PATH_DIR="$SCRIPT_DIR"
elif [ -f "$SCRIPT_DIR/../../../$EM_JAR" ]
then
    # we are in app directory
    EM_PATH="$SCRIPT_DIR/../../../$EM_JAR"
    EM_PATH_DIR="$SCRIPT_DIR/../../.."
    IN_APP="yes"
else
    echo "Can not find $EM_JAR"
    exit
fi

JDK_PATH="$EM_PATH_DIR/../../../jdk"
sdkInfoPath="$EM_PATH_DIR/../../../sdk.info"
setJavaExecPath

# run
if [ -z "$IN_APP" ]
then
    "$JAVA_EXEC" -jar "$EM_PATH" "$@"
else
    "$JAVA_EXEC" -jar "$EM_PATH"
fi
