#!/bin/bash

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="dynamic-analyzer_$date_time.txt"
    if [ ! -d "${sdkDataPath}/dynamic-analyzer/logs" ]; then
        mkdir -p "${sdkDataPath}/dynamic-analyzer/logs"
    fi
    logFilePath="$sdkDataPath/dynamic-analyzer/logs/$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
		JAVA_EXEC="$JDK_PATH/Contents/Home/bin/java"
    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)"
/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -f certificate-manager.app
JDK_PATH="$SCRIPT_DIR/../../../../../jdk"
sdkInfoPath="$SCRIPT_DIR/../../../../../sdk.info"

setJavaExecPath

# get script path
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

# path definition
BIN_DIR_PATH="${SCRIPT_PATH}/../../.."
LAUNCHER_JAR="${BIN_DIR_PATH}/plugins/org.eclipse.equinox.launcher_*"
ICON_FILE="${SCRIPT_PATH}/../Resources/DA_icon.icns"

# launch dynamic analyzer by java command
"${JAVA_EXEC}" \
-XX:MaxPermSize=64m \
-Xms256m \
-Xmx512m \
-XX:+UseParNewGC \
-XX:+UseConcMarkSweepGC \
-XX:+IgnoreUnrecognizedVMOptions \
-Xdock:icon=$ICON_FILE \
-XstartOnFirstThread \
-Dorg.eclipse.swt.internal.carbon.smallFonts \
-Dosgi.requiredJavaVersion=1.7 \
--add-modules=ALL-SYSTEM \
-jar $LAUNCHER_JAR
