#!/bin/bash

javaCommand=""

cd /

if [ -f "/etc/xdl/ctx-jproxy.conf" -a -s "/etc/xdl/ctx-jproxy.conf" ]; then
    . "/etc/xdl/ctx-jproxy.conf"
else
    echo "Error: config file /etc/xdl/ctx-jproxy.conf not found or empty."
    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/jproxy-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/jproxy-debug.log
fi

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)"
        #Support RHEL7.9 on AWS
        if [ -z "$jpath" ]; then
            jpath="$(find /usr/lib/jvm/ -type d -name "msopenjdk*" | sort -d -r | head -n 1)"
        fi

        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
}

VdaPid=0
Terminate=0

kill_jproxy() {
    Terminate=1
}

vda_running() {
    kill -0 $VdaPid
}

trap kill_jproxy SIGTERM SIGINT

export LD_LIBRARY_PATH="/opt/Citrix/VDA/lib64"

jvm_args() {
    echo -n " -Xmx1024m"
    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"
    echo -n " -Djava.util.prefs.PreferencesFactory=$ConfigBackend"
    echo -n " -Dcom.citrix.cds.brokeragent.dburl=$ConfigDbUrl"
    echo -n " -Dcom.citrix.cds.brokeragent.dbcred=/etc/xdl/ctx-jproxy.conf"

    # below args should be used when debugging with visualvm
    # fqdn=`hostname -f`
    # echo -n " -Djava.rmi.server.hostname=$fqdn"
    # echo -n " -Dcom.sun.management.jmxremote"
    # echo -n " -Dcom.sun.management.jmxremote.port=9199"
    # echo -n " -Dcom.sun.management.jmxremote.authenticate=false"
    # echo -n " -Dcom.sun.management.jmxremote.ssl=false"

    # heap dump on OOM
    # echo -n " -XX:+HeapDumpOnOutOfMemoryError"
    # echo -n " -XX:HeapDumpPath=/tmp/jproxy.hprof"

    if [ -n "$Log4jConfig" -a -f "$Log4jConfig" ]; then
        echo -n " -Dlog4j.configurationFile=${Log4jConfig}"
    fi

    UserHz=$(getconf CLK_TCK)
    if  [ ! $? ] ; then
	# Assume the typical default
	UserHz=100
    fi
    echo -n " -Duserhz=$UserHz"

    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=0.0.0.0:1044,suspend=y"
    fi
}

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

if [ "${InteractiveDebugMode:=0}" -gt 0 ]; then
    $javaCommand $(jvm_args) -jar /opt/Citrix/VDA/lib64/ctx-proxy.jar
else
    $javaCommand $(jvm_args) -jar /opt/Citrix/VDA/lib64/ctx-proxy.jar &
    VdaPid=$!
    echo "-999" > /proc/$VdaPid/oom_score_adj

    # wait until we are signaled to terminate or vda terminates itself
    while [ $Terminate -eq 0 ]; do
        wait $VdaPid
        if ! vda_running; then
            Terminate=1
        fi
    done

    # vda terminated without our signal, abnormal
    if ! vda_running; then
        exit 1
    fi

    # signal vda to terminate
    kill -TERM $VdaPid

    # wait up to 3 secs for vda to terminate itself
    retry=0
    while vda_running && [ $retry -lt 3 ]; do
        sleep 1
        let retry=$(($retry + 1))
    done

    # finally, if vda still hangs, kill it
    if vda_running; then
        kill -KILL $VdaPid
    fi
fi

exit 0
