#!/bin/sh

PRG="$0"
saveddir=`pwd`
EOS_DAP_HOME=`dirname "$PRG"`/..
EOS_DAP_HOME=`cd "$EOS_DAP_HOME" && pwd`
cd "$saveddir"

export APP_NAME=DAMP
export MODE=service
export LOG_FOLDER="${EOS_DAP_HOME}"/logs
export PID_FOLDER="${LOG_FOLDER}"
export LOG_FILENAME="${APP_NAME}.out" # log console for background mode running

mkdir -p $LOG_FOLDER/$APP_NAME       # pid dir

rm -fr $LOG_FOLDER/$LOG_FILENAME
ln -s /dev/null $LOG_FOLDER/$LOG_FILENAME             # "$LOG_FOLDER/$LOG_FILENAME is using for >> "$log_file" 2>&1"

export EOS_DAP_MEM_OPTS="-Xms512m -Xmx2048m -Xmn256m"

export JAVA_OPTS="$JAVA_OPTS -Djava.net.preferIPv4Stack=true -Duser.timezone=Asia/Shanghai -Dclient.encoding.override=UTF-8 -Dfile.encoding=UTF-8 -Djava.security.egd=file:/dev/./urandom"
export JAVA_OPTS="$JAVA_OPTS $EOS_DAP_MEM_OPTS"
export JAVA_OPTS="$JAVA_OPTS -XX:+HeapDumpOnOutOfMemoryError"
export JAVA_OPTS="$JAVA_OPTS -DEXTERNAL_CONFIG_DIR=${EOS_DAP_HOME}/config"
export JAVA_OPTS="$JAVA_OPTS -Dloader.path=${EOS_DAP_HOME}/lib"
export JAVA_OPTS="$JAVA_OPTS -Dlogging.config=${EOS_DAP_HOME}/config/logback-spring.xml"
export JAVA_OPTS="$JAVA_OPTS -Dnacos.logging.path=${LOG_FOLDER}/nacos -Dcom.alibaba.nacos.naming.cache.dir=${LOG_FOLDER}/nacos/cache"

# export JAVA_OPTS="$JAVA_OPTS -XX:+UseParNewGC -XX:ParallelGCThreads=4 -XX:MaxTenuringThreshold=9 -XX:+UseConcMarkSweepGC"

if [[ "$*" =~ "-debug" ]]; 
then
    export JAVA_OPTS="$JAVA_OPTS -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8788"
fi

if [[ "$*" =~ "-apm" ]]; 
then
    export JAVA_OPTS="$JAVA_OPTS -javaagent:${EOS_DAP_HOME}/../../skywalking-agent/skywalking-agent.jar"
    export JAVA_OPTS="$JAVA_OPTS -DSW_AGENT_NAME=${APP_NAME}"
    export JAVA_OPTS="$JAVA_OPTS -Dskywalking.trace.ignore_path=/eureka/**,/actuator/eos/**,/nacos/**"
    #export JAVA_OPTS="$JAVA_OPTS -DSW_AGENT_COLLECTOR_BACKEND_SERVICES=127.0.0.1:11800"
fi

export JAVA_OPTS="$JAVA_OPTS $FORCE_JAVA_OPTS"

if [[ "$*" =~ "-opens" ]];
then
    export JAVA_OPTS="$JAVA_OPTS --add-opens java.base/java.lang=ALL-UNNAMED"
fi

action=$1
if [[ "$action" == "run" ]] || [[ "$action" == "start" ]]; 
then
  shift
else
  action="start"
fi

if [[ "$*" =~ "-version" ]]; 
then
    export JAVA_OPTS="$JAVA_OPTS -Dloader.main=com.primeton.eos.springboot.VersionInfo"
    action="run"
fi

BOOT_JAR=`echo "${EOS_DAP_HOME}"/*.jar`
$BOOT_JAR $action "$@"

