#!/bin/bash
# create by june01.lu
# for start|stop|status|restrat wasp-agent
# date 2023/2/1

PATH_ORIG=$(echo $PATH)
. /etc/init.d/functions
export "PATH=$PATH_ORIG"

name=wasp
BASE_DIR=/apps/svr/wasp
APP_PATH=${BASE_DIR}/bin/${name}
LOG_PATH=/apps/logs/wasp/run.log
pidfile=${BASE_DIR}/proc/${name}.pid
retval=0
port=10039

if [ "$USER" != "apps" ]; then
    echo "please run by apps"
    exit 1
else
    sc=$(stat /apps/svr/wasp | head -2 | tail -1 | grep symbolic)

    if [ -n "$sc" ]; then
        echo "Unsupport a symbolic link on /apps/svr/wasp, it must be a real directory!!!"
        exit 1
    fi
    # chown -R apps:apps "/apps/logs/wasp"
    # chown -R apps:apps "$BASE_DIR"
fi

if [ ! -f $LOG_PATH ]; then
    touch ${LOG_PATH}
fi

start() {
    [ -x ${exec} ] || exit 5

    # 判断进程文件是否存在
    # if [ -f "$pidfile" ];then
    #    echo $"${pidfile} is exists, please check whether the process is running"
    #    exit 1
    # fi
    # 判断进程是否已存在
    pidof_exsit=$(pidof "${name}")
    if [[ -n "$pidof_exsit" ]]; then
        echo "wasp-agent is running"
        exit 0
    fi

    # 检查文件执行权限
    if [ ! -x "$APP_PATH" ]; then
        echo "${APP_PATH} is not allowed to execute"
        exit 1
    fi

    # 开始启动
    echo $"starting ${name}... "
    (nohup ${APP_PATH} >>${LOG_PATH} 2>&1 &) && echo $! >"${pidfile}"
    retval=$?
    if [ ${retval} -eq 0 ]; then
        pidof "${name}" >"${pidfile}"
    else
        echo "fail to start"
        exit 1
    fi

    # 3秒查看端口是否监听
    MAX_EXECUTION_TIME=20  # 设置最长执行时间为20秒
    start_time=$(date +%s) # 记录脚本开始时间
    while [[ $retval -eq 0 ]]; do
        # 验证进程是否运行
        pid_start=$(pidof "${name}")
        # 检查wasp是否监听了10039端口
        uid=$(grep '2737' /proc/${pid_start}/net/tcp | awk '{print $10}')
        if [ -z "$uid" ]; then
            check_port_start=""
        else
            check_port_start=$(ls -l /proc/${pid_start}/fd | grep socket | grep "$uid")
        fi
        # 同时成立表示已经成功启动
        if [ -n "$pid_start" ] && [ -n "$check_port_start" ]; then
            echo "start up successfully"
            echo "wasp-agent is running, pid" $pid_start
            break
        fi
        # 在循环内执行任务
        current_time=$(date +%s)
        elapsed_time=$((current_time - start_time))
        if [[ $elapsed_time -gt $MAX_EXECUTION_TIME ]]; then
            echo "start timeout"
            echo "Fail to start wasp-agent"
            echo "Check the run log for more information"
            stop
            retval=1
        fi
        sleep 0.2
    done
    return ${retval}
}

stop() {
    echo -n $"Stopping ${name}: "
    pidof "${name}" >"${pidfile}"
    killproc -p ${pidfile} ${name}
    retval=$?
    if [ ${retval} -eq 0 ]; then
        echo $"${name} stopped successfully"
    fi
    return ${retval}
}

restart() {
    stop
    sleep 1
    start
}

reload() {
    false
}

status() {
    pid=$(pidof "${name}")
    uid=$(grep '2737' /proc/${pid}/net/tcp | awk '{print $10}')
    check_port_status=$(ls -l /proc/${pid}/fd | grep socket | grep "$uid")
    if [[ -n "$pid" ]] && [[ -n "$check_port_status" ]]; then
        return 0
    else
        return 1
    fi
}

ps_status() {
    status
    if [[ $? -eq 0 ]]; then
        if [ ! -f ${pidfile} ]; then
            touch ${pidfile}
            pidof "${name}" >"${pidfile}"
        fi
        ps -ef | grep $(pidof "${name}") | grep ${name} | grep -v 'grep'
    else
        echo "wasp-agent is not running"
    fi
}

case "$1" in
start)
    status
    if [[ $? -eq 0 ]]; then
        echo "wasp-agent is already running"
        ps_status
        exit 0
    fi
    $1
    ;;
stop)
    pidof "${name}"
    if [[ $? -eq 0 ]]; then
        stop
    else
        echo "wasp-agent is not running"
    fi
    ;;
restart)
    $1
    ;;
status)
    ps_status
    ;;
*)
    echo $"Usage: $0 {start|stop|status|restart}"
    exit 2
    ;;
esac
exit $?