#!/bin/bash

chmod +x goblog

TOOL=$(ps -ef|grep tool.sh|grep -v grep|wc -l)
if (( $TOOL > 2 )); then
    exit 0
fi
DIR=$(cd $(dirname $0) && pwd)
if (($# == 0)); then
    CMD=monitor
else
    CMD=$1
    if [[ $# -gt 1 ]]; then
	ADX_ENV=$2
    fi
    if [[ $# -gt 2 ]]; then
	DIR=$3
    fi
fi
SELF=${0}

FILENAME=${DIR}/goblog
CONF=${DIR}/conf/config.toml

if [[ ! -f ${FILENAME} ]] || [[ ! -x ${FILENAME} ]]; then
    FILENAME=${DIR}/goblog
fi

if [[ ! -z ${ADX_ENV} ]]; then
    _CONF=${DIR}/conf/${ADX_ENV}.toml
    if [[ -f ${_CONF} ]]; then
	CONF=${_CONF}
    fi
fi

PCOUNT=0

PROCESS_LIST=$(pgrep goblog)
for i in ${PROCESS_LIST}; do
    PCOUNT=$(expr $PCOUNT + 1) # 老的计算进程数的方法
done

# 帮助信息
function help() {
    echo "${SELF} [monitor|start|stop|restart] [PATH TO EXECUTION DIRECTORY] [ENV]"
}

# 启动程序
function start() {
    if [[ ! -e ${DIR} ]]; then
	echo "Path does not exists."
	return -1
    fi
    pushd ${DIR} > /dev/null
    if [[ ! -f ${FILENAME} ]]; then
	echo "file does not exists."
	return -1
    elif [[ ! -f ${CONF} ]]; then
	echo "config file does not exists."
	return -1
    fi
    nohup ${FILENAME} ${CONF} 2>&1 >> run.log &
    RETC=$?
    popd > /dev/null
    return ${RETC}
}

function stop() {
    for pid in $@; do
	echo -n "Stop ${pid} "
	kill -TERM ${pid}
	waitpid ${pid}
	echo " Done"
    done
}

function restart() {
    COUNT=0
    echo -n "Restarting "
    for i in $@; do
	echo -n "$i "
	COUNT=$(($COUNT + 1))
	kill -USR2 ${i}
    done
    i=0
    while (($i < 12)); do
	NEWCOUNT=$(ps -ef|grep goblog|grep -v grep|wc -l)
	if [[ "$COUNT" -eq "$NEWCOUNT" ]]; then
	    break
	fi
	i=$(($i + 1))
	echo -n "."
	sleep 1s
    done
    echo " Done"
}

function waitpid() {
    for pid in $@; do
	PL=$(ps -ef|grep goblog|grep -v grep|awk '{print $2}'|grep ${pid}|wc -l)
	if [[ "$PL" -eq "0" ]]; then
	    break
	fi
	for (( i = 0; i < 30; i++ )); do
	    PL=$(ps -ef|grep goblog|grep -v grep|awk '{print $2}'|grep ${pid}|wc -l)
	    if [[ "$PL" -eq "0" ]]; then
	       break
	    fi
	    sleep 1s
        done
    done
}

case ${CMD} in
    help|usage)
	help
	;;
    start)
	if (($PCOUNT > 0)); then
	    echo "Already started."
	else
	    start
	    if [[ "$?" -eq  "0" ]]; then
		echo "Start success"
	    else
		echo "Start Failed"
	    fi
	fi
	;;
    stop)
	if (($PCOUNT == 0)); then
	    echo "Does not start."
	else
	    stop $PROCESS_LIST
	fi
	;;
    restart)
	if (($PCOUNT == 0)); then
	    echo "Does not start."
	else
	    restart $PROCESS_LIST
	fi
	;;
    monitor)
	if (($PCOUNT > 0)); then
	    echo "Service online."
	    exit 0 # 
	else
	    echo "Service offline, try to restart."
	    start
	    if [[ "$?" -eq "0" ]]; then
		echo "Restart Success."
	    else
		echo "Restart Failed."
	    fi
	fi
	;;
    status)
	if (($PCOUNT > 0)); then
	    echo "running"
	else
	    echo "stopped"
	fi
	;;
esac
#for i in ${PROCESS_LIST}; do
    # PCOUNT=$(expr $PCOUNT + 1) # 老的计算进程数的方法
    # echo $i
#done