#!/bin/bash
### check argument count ###
if [ $# -eq 0 ]
then
   echo "Error: Argument missing. Use '-h' for help."
   exit
fi


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="emCli_$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
}

#set JAVA_EXEC : relative path to embedded jdk
#read the contents of sdk.info to get the jdk path

SCRIPT_DIR="$(cd "$(dirname "$0")" ; pwd -P)"
JDK_PATH="$SCRIPT_DIR/../../../jdk"
sdkInfoPath="$SCRIPT_DIR/../../../sdk.info"

setJavaExecPath


### find location of script file ###
pushd . > /dev/null
SCRIPT_PATH="${BASH_SOURCE[0]}";
    while([ -h "${SCRIPT_PATH}" ]) do
        cd "`dirname "${SCRIPT_PATH}"`"
        SCRIPT_PATH="$(readlink "`basename "${SCRIPT_PATH}"`")";
    done
cd "`dirname "${SCRIPT_PATH}"`" > /dev/null
SCRIPT_PATH="`pwd`";
popd > /dev/null
#echo "script=[${SCRIPT_PATH}]"
###

em_path=`echo "${SCRIPT_PATH}/em-cli.jar"`
#echo "em_path=[${em_path}]"

current_path=`pwd`
current_emulmgr="$current_path/em-cli.jar"

export COLUMNS="$[$(tput cols)]"

if [ -f "$current_emulmgr" ]
then
"$JAVA_EXEC" -jar "$current_emulmgr" "$@"
else
"$JAVA_EXEC" -jar "$em_path" "$@"
fi
