#!/usr/bin/env bash
#chkconfig: 35 20 80
#description: Agent server

basePath=$(cd `dirname $0`/; pwd)
baseDirPath="${basePath}"
serviceName=$(basename ${basePath})
serviceRegisterAddr="/etc/rc.d/init.d"
pid=
port=
addOpens="--add-opens=java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.io=ALL-UNNAMED --add-opens java.base/java.math=ALL-UNNAMED --add-opens java.base/java.net=ALL-UNNAMED --add-opens java.base/java.nio=ALL-UNNAMED --add-opens java.base/java.security=ALL-UNNAMED --add-opens java.base/java.text=ALL-UNNAMED --add-opens java.base/java.time=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/jdk.internal.access=ALL-UNNAMED --add-opens java.base/jdk.internal.misc=ALL-UNNAMED --add-opens java.base/jdk.internal.loader=ALL-UNNAMED --add-opens java.base/sun.net=ALL-UNNAMED --add-opens java.naming/com.sun.jndi.ldap=ALL-UNNAMED"

uniqueId="9d2b53e"
packageName=$(basename `find ${basePath}/*.jar`)

function getPid()
{
    pid=`pgrep java| xargs --no-run-if-empty ps -fp | grep ${baseDirPath}/${packageName} | awk '{print $2}'`
}

function start()
{
    getPid
    if [[ ${pid} ]]
    then
        echo "Agent already running."
        return 0
    fi
    . /etc/profile
    if [[ $(basename $0) != "cloudBridge.sh" ]]
    then
        basePath=$(basename $0)
        eval basePath=$(echo \$${basePath})
        packageName=$(basename `find ${basePath}/*.jar`)
        configPath=$(find ${basePath}/config/*.yml)
        nohup java -Xms256m -Xmx384m ${addOpens} -jar ${basePath}/${packageName} --spring.config.location=${configPath} >${basePath}/log/agent.log 2>&1 &
    else
        cd ${baseDirPath}

        if [[ -f "${packageName}" ]]
        then
            nohup java -Xms256m -Xmx384m ${addOpens} -jar ${baseDirPath}/${packageName} >${baseDirPath}/log/agent.log 2>&1 &
            sleep 10
            getPid
            if [[ ${pid} ]]
            then
                echo "Starting Agent Success."
            else
                echo "Starting Agent Fail."
            fi
        else
            echo "The Agent jar is not found."
        fi
    fi
}

function stop()
{
    getPid
    if [[ ${pid} ]]
    then
        stopStatus="N"
        read -p "Agent is running, please confirm to stop: (y or n) " stopStatus
        if [[ ${stopStatus^^} == "Y" ]]
        then
            kill -9 ${pid}
            sleep 3
            getPid
            if [[ ${pid} ]]
            then
                echo "Stop Agent Fail."
            else
                echo "Stop Agent Success."
            fi
        fi
    fi
}

function restart()
{
    getPid
    if [[ ${pid} ]]
    then
        restartStatus="N"
        read -p "Agent is running, please confirm to restart: (y or n) " restartStatus
        if [[ ${restartStatus^^} == "Y" ]]
        then
            kill -9 ${pid}
            sleep 3
            cd ${baseDirPath}

            if [[ -f "${packageName}" ]]
            then
                . /etc/profile
                nohup java -Xms256m -Xmx384m ${addOpens} -jar ${baseDirPath}/${packageName} >${baseDirPath}/log/agent.log 2>&1 &
            fi
            sleep 10
            getPid
            if [[ ${pid} ]]
            then
                echo "Restart Agent Success."
            else
                echo "Restart Agent Fail."
            fi
        else
            echo "Restart the cancel."
        fi
    else
        echo "No Agent running."
    fi
}

function check()
{
    getPid
    if [[ ${pid} ]]
    then
        getPort
        health=`curl --connect-timeout 10 -m 20 "http://127.0.0.1:${port}/status/health"`
        status=`echo ${health} | sed 's/,/\n/g' | grep "health" | sed 's/:/\n/g' | sed '1d' | sed 's/}//g'`
        if [[ ${status} != "true" ]]
        then
            reason=`echo ${health} | sed 's/,/\n/g' | grep "reason" | sed 's/:/\n/g' | sed '1d' | sed 's/}//g'`
            kill -9 ${pid}
            sleep 3
            start
            if [[ $? -eq 0 ]]
            then
                echo "time: $(date);reason:${reason};operation:restart;result:success" >> ${baseDirPath}/log/watchDog$(date +"%Y-%m-%d").log
            else
                echo "time: $(date);reason:${reason};operation:restart;result:fail" >> ${baseDirPath}/log/watchDog$(date +"%Y-%m-%d").log
            fi
        fi
      else
          start
        if [[ $? -eq 0 ]]
        then
            echo "time: $(date);reason:agent down;operation:start;result:success" >> ${baseDirPath}/log/watchDog$(date +"%Y-%m-%d").log
        else
            echo "time: $(date);reason:agent down;operation:start;result:fail" >> ${baseDirPath}/log/watchDog$(date +"%Y-%m-%d").log
        fi
      fi
}

function getPort() {
    getPid
    port=`netstat -anp | grep ${pid} | awk -F '[:::]+' '{print $2}' | head -1 | sed s/[[:space:]]//g`
}


function deleteWatchLog() {
    rm -f `find ${baseDirPath}/log/ -mtime +30 -name "watchDog*.log"`
}

if [[ ${#} -ge 1 ]]
then
    case ${1} in
        "start")
            start
        ;;
        "restart")
            restart
        ;;
        "stop")
            stop
        ;;
        "getPid")
            getPid
        ;;
        "check")
            check
        ;;
        "deleteWatchLog")
            deleteWatchLog
        ;;
        *)
            echo "${1} No operation"
        ;;
    esac
else
    echo "
    command: start/stop/restart

    command example: ./cloudbridge start
    "
fi
