#!/bin/bash
cd `dirname $0`
CUR_SHELL_DIR=`pwd`
CUR_SHELL_NAME=`basename ${BASH_SOURCE}`
#修改这里jar包名即可
JAR_NAME="guthon-file-transfer.jar"
PIDFILE="tomcat.pid"  # PID文件路径

JAR_PATH=$CUR_SHELL_DIR/$JAR_NAME
JAVA_MEM_OPTS=" -server -Xms512m -Xmx4g -Dfile.encoding=UTF-8  -Duser.timezone=GMT+08"
SPRING_PROFILES_ACTIV=""
LOG_DIR=$CUR_SHELL_DIR/logs
LOG_PATH=$LOG_DIR/${JAR_NAME}.log

# 若存在用户自定义文件，则尝试加载他，已实现用户个性化环境变量配置需求
if [ -f "$CUR_SHELL_DIR/env.sh" ]; then
    source "$CUR_SHELL_DIR/env.sh"
fi

EXEC_JAVA="java"
# 强制指定JDK8
#JAVA_HOME=/opt/guthon/servo-client/jdk8
if [ "$JAVA_HOME" != "" ]; then
    EXEC_JAVA="$JAVA_HOME/bin/java"
fi

echo_help()
{
    echo -e "syntax: sh $CUR_SHELL_NAME start|stop"
}

if [ -z $1 ];then
    echo_help
    exit 1
fi

if [ ! -d "$LOG_DIR" ];then
    mkdir "$LOG_DIR"
fi

if [ ! -f "$LOG_PATH" ];then
    touch "$LOG_DIR"
fi

if [ -f "$PIDFILE" ]; then
    PID=$(cat $PIDFILE)           # 将PID从文件中读取，并作为一个变量
fi

if [ "x$PID" != "x" ]; then
    PIDS=`ps --no-heading -p $PID | awk '{print $1}'`
fi

if [ "$1" == "start" ];then
    # check server
    if [ -n "$PIDS" ]; then
        echo -e "ERROR: The $JAR_NAME already started and the PID is ${PIDS}."
        exit 1
    fi

    echo "Start SpringBoot Service $JAR_NAME..."
	rm -rf $LOG_PATH # 删除启动日志
    nohup $EXEC_JAVA $JAVA_MEM_OPTS -jar $SPRING_PROFILES_ACTIV $JAR_PATH -X$PWD >> $LOG_PATH 2>&1 &
    
    COUNT=0
    while [ $COUNT -lt 1 ]; do
        sleep 1
        COUNT=`ps  --no-heading -C java -f --width 1000 | grep "$JAR_NAME -X$PWD" | awk '{print $2}' | wc -l`
	if [ $COUNT -gt 0 ]; then
            break
        fi
    done

    PIDS=`ps  --no-heading -C java -f --width 1000 | grep "$JAR_NAME -X$PWD" | awk '{print $2}'`
    echo "${JAR_NAME} Started and the PID is ${PIDS}."
elif [ "$1" == "stop" ];then
    if [ -z "$PIDS" ]; then
        echo "ERROR:The $JAR_NAME does not started!"
        exit 1
    fi 
    
    echo -e "Stopping the $JAR_NAME[$PIDS]..."
    kill $PID > /dev/null 2>&1

    COUNT=30
    while [ $COUNT -gt 0 ]; do
        sleep 1
        PIDS=`ps --no-heading -p $PID | awk '{print $1}'`
        if [ "x$PIDS" = "x" ]; then
            COUNT=0
            break
        fi
	
        let COUNT--
        echo "wait service shutdown[$COUNT]s..."
        if [ $COUNT -eq 10 ]; then
            echo "The service is not shutdown, now kill it!"
            kill $PID -9 > /dev/null 2>&1
        fi

        if [ $COUNT -eq 1 ]; then
            echo "WARN: server is not shutdown !!!!"
        fi
    done
    
    if [ -f "$PIDFILE" ]; then # 如果PID文件存在，则删除
        rm -rf $PIDFILE
    fi
    
    echo -e "${JAR_NAME} Stopped and the PID is ${PID}."
fi


