#######################################################################################################################
# Java 应用进程管理脚本
#######################################################################################################################
#!/bin/bash

jarfile_name="spiderlab-dagent.jar"

# 启动进程
start() {
    pid=`jps | grep ${jarfile_name} | awk '{print $1}'`
    if [ ! -z ${pid} ]
    then
        echo "${jarfile_name} has been running with pid ${pid}..."
        exit 0
    fi

    nohup java -jar ${jarfile_name} > console.log 2>&1 &

    declare count=0
    declare max=60
    while [[ ${count} -lt ${max} && -z ${pid} ]]; do
        ((count++))
        echo "sleep ${count}s to wait ${jarfile_name} start..."
        sleep 1
        pid=`jps | grep ${jarfile_name} | awk '{print $1}'`
    done

    if [ ${count} -gt ${max} ]; then
        echo "${jarfile_name} started failed..."
        exit 1
    else
        echo "${jarfile_name} has been started with pid ${pid}..."
        exit 0
    fi
}

# 结束进程
stop() {
    pid=`jps | grep ${jarfile_name} | awk '{print $1}'`
    if [ -z ${pid} ]
    then
        echo "${jarfile_name} not running..."
    else
        kill -15 ${pid}

        oldpid=${pid}
        declare count=0
        declare max=60
        while [[ ${count} -lt ${max} && ! -z ${pid} ]]; do
            ((count++))
            echo "sleep ${count}s to wait ${jarfile_name} shutdown..."
            sleep 1
            pid=`jps | grep ${jarfile_name} | awk '{print $1}'`
        done

        if [ ${count} -gt ${max} ]; then
            echo "${jarfile_name} shutdown failed..."
            exit 1
        else
            echo "${jarfile_name} with pid ${oldpid} has been killed..."
            exit 0
        fi
    fi
}

case $1 in
start)
    start
    ;;
stop)
    stop
    ;;
restart)
    stop
    start
    ;;
*)
    echo "Usage: sh runner.sh [start|stop|restart]"
    exit 1
    ;;
esac