#!/bin/sh

javaCommand=""

# Set this flag to 1 to enter debugging mode
DebugMode=0
# Set this flag to 1 to enter interactive debugging mode
InteractiveDebugMode=0

find_java_command() {
    if [ -z "$javaCommand" ]; then
        javaCommand="java"
        #RHEL, UBUNTU, DEBIAN
        jpath="$(find /usr/lib/jvm/ -type d -name "java-11-openjdk*" | sort -d -r | head -n 1)"
        if [ -n "$jpath" ] && command -v $jpath/bin/java &> /dev/null; then
            javaCommand=$jpath/bin/java
            return 0
        fi
        #SUSE
        if command -v /usr/lib64/jvm/jre-11-openjdk/bin/java &> /dev/null; then
            javaCommand=/usr/lib64/jvm/jre-11-openjdk/bin/java
            return 0
        fi
    fi

    if command -v $javaCommand &> /dev/null; then
        return 0
    else
        return 1
    fi
}

if ! find_java_command; then
    echo -n "JAVA command not found!"
    exit 1
fi

if [ "$DebugMode" -eq 0 ]; then
    # Now give up the terminal
    exec >/dev/null
    exec 2>&1
else
    # Redirect to debug log file
    exec >/var/log/xdl/telemetry-debug.log
    exec 2>&1
    echo "Info: ctxjproxy debug mode enabled. This file will reset on service start or restart."
    chmod o-r /var/log/xdl/telemetry-debug.log
fi


# The file name of Telemetry Service log file
LogFile="/var/log/xdl/telemetry.log"
PerfLogFile="/var/log/xdl/telemetryperf.log"

jvm_args() {
    echo -n " -Dlogfile=$LogFile"
    echo -n " -Dperflogfile=$PerfLogFile"
    echo -n " -Dfile.encoding=UTF8"
    echo -n " -Dsun.security.krb5.msinterop.kstring=true"
    echo -n " -Djavax.security.auth.useSubjectCredsOnly=false"

    if [ "$DebugMode" -gt 0 ]; then
        echo -n " -Dsun.security.krb5.debug=true"
        echo -n " -Dsun.security.jgss.debug=true"
    fi

    if [ "${InteractiveDebugMode:=0}" -gt 0 ]; then
        echo -n " -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8083,suspend=y"
    fi
}

bit=`getconf LONG_BIT`
if [ $bit -eq 64 ]; then
    $javaCommand $(jvm_args) -jar /opt/Citrix/VDA/lib64/ctx-telemetry.jar
else
    $javaCommand $(jvm_args) -jar /opt/Citrix/VDA/lib32/ctx-telemetry.jar
fi

exit 0
