#!/bin/bash -e

# chkconfig: - 99 00
# description: Wavefront Proxy

### BEGIN INIT INFO
# Provides:          wavefront-proxy
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Required-Start:
# Required-Stop:
### END INIT INFO

################################################################################
# File any issues here: https://github.com/wavefrontHQ/java/issues.
################################################################################

service_name="wavefront-proxy"
sysconfig="/etc/sysconfig/$service_name"
[[ -f "$sysconfig" ]] && . $sysconfig

desc=${DESC:-Wavefront Proxy}
pid_file=${PID_FILE:-/var/run/$service_name.pid}

setupEnv(){
    if [ -f /.dockerenv ]; then
        >&2 echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
        >&2 echo "WARNING: Attempting to start Wavefront Proxy as a system daemon in a container environment."
        >&2 echo "'service wavefront-proxy' commands are for stand-alone installations ONLY."
        >&2 echo "Please follow Docker-specific install instructions in the 'Add a Wavefront Proxy' workflow"
        >&2 echo "(In Wavefront UI go to Browse menu -> Proxies -> Add -> select 'Docker' tab)"
        >&2 echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
    fi

    if [ -n "${PROXY_JAVA_HOME}" ]; then
        echo "using JRE in `${PROXY_JAVA_HOME}`(PROXY_JAVA_HOME) as JAVA_HOME"
        JAVA_HOME = ${PROXY_JAVA_HOME}
    else
        if [ -n "${JAVA_HOME}" ]; then
            echo "using JRE in \"${JAVA_HOME}\" (JAVA_HOME)"
        else
            JAVA_HOME=$(readlink -f $(which java) | sed "s:/bin/java::")
            if [ -d "${JAVA_HOME}" ]; then
                echo "using JRE in \"${JAVA_HOME}\" ($(which java))"
            else 
                echo "Error! JAVA_HOME (or PROXY_JAVA_HOME) not defined, use `${sysconfig}` file to define it"
                exit -1
            fi
        fi
    fi

    user="wavefront"
    wavefront_dir="/opt/wavefront"
    proxy_dir=${PROXY_DIR:-$wavefront_dir/wavefront-proxy}
    config_dir=${CONFIG_DIR:-/etc/wavefront/wavefront-proxy}

    conf_file=$CONF_FILE
    if [[ -z $conf_file ]]; then
        legacy_config_dir=$proxy_dir/conf
        if [[ -r "$legacy_config_dir/wavefront.conf" ]]; then
            conf_file="$legacy_config_dir/wavefront.conf"
            >&2 echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
            >&2 echo "WARNING: Using wavefront.conf file found in its old location ($legacy_config_dir)."
            >&2 echo "To suppress this warning message, please move wavefront.conf to $config_dir."
            >&2 echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
        else
            conf_file="$config_dir/wavefront.conf"
        fi
    fi
    echo "Using \"${conf_file}\" as config file"

    log_file="/var/log/wavefront/wavefront.log"
    proxy_jar=${AGENT_JAR:-$proxy_dir/bin/wavefront-proxy.jar}
    class="com.wavefront.agent.WavefrontProxyService"
    app_args=${APP_ARGS:--f $conf_file}

    # If JAVA_ARGS is not set, try to detect memory size and set heap to 8GB if machine has more than 8GB.
    # Fall back to using AggressiveHeap (old behavior) if less than 8GB.
    if [[ -z "$JAVA_ARGS" ]]; then
        if [ `grep MemTotal /proc/meminfo | awk '{print $2}'` -gt "8388607" ]; then
            java_args=-Xmx8g
            >&2 echo "Using default heap size (8GB), please set JAVA_ARGS in /etc/sysconfig/wavefront-proxy to use a different value"
        else
            java_args=-XX:+AggressiveHeap
        fi
    else
        java_args=$JAVA_ARGS
    fi

    jsvc=$proxy_dir/bin/jsvc
}

jsvc_exec()
{
    setupEnv

    nohup ${JAVA_HOME}/bin/java \
		$java_args \
		-Dlog4j.configurationFile=$config_dir/log4j2.xml \
		-Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager \
		-jar $proxy_jar \
		$app_args >> ${log_file} 2>&1 &
    
    echo $! > $pid_file
}

start()
{
    if [[ -f "$pid_file" ]]; then
        echo "$desc is already running (PID $(cat "$pid_file"))"
    fi
    echo "Starting $desc"
    jsvc_exec
    echo "Done"
}

status()
{
    if [[ -f "$pid_file" ]]; then
        echo "$desc is running (PID $(cat "$pid_file"))"
    else
        echo "$desc is not running."
        exit 3
    fi
}

stop()
{
    if [[ -f "$pid_file" ]]; then
        echo "Stopping $desc"
        PID=$(cat $pid_file);
        kill $PID;
        rm ${pid_file}
        echo "Done"
    else
        echo "$desc is not running."
    fi
}

restart()
{
    stop
    start
}

condrestart()
{
    [ -f "$pid_file" ] && restart || :
}

case "$1" in
start) start ;;
status) status ;;
stop) stop ;;
restart) restart ;;
condrestart) condrestart ;;
*)
	echo "Usage: $0 {status | start | stop | restart | condrestart}"
	exit 1
esac
