
export LANG=zh_CN.utf8
export LC_ALL=zh_CN.utf8

#改变工作目录到当前脚本所在路径
if [[ "$0" =~ / ]]; then cd "${0%/*}"; fi

export CWD=`pwd`

if [[ "$MATRIXROOT" == "" ]]; then
    export MATRIXROOT="/opt/matrix"
fi

export STDERROR=$MATRIXROOT/var/logs/datasync/out.log

printusage(){
    echo "type '${0} stop' to stop it"
    echo "  or '${0} restart' to restart it"
    echo "  or '${0} status' to check status"
    echo "cat $STDERROR for detail information"
}

#检查正在运行的实例
pid=`ps -ef | grep "$CWD/datasync" | grep -v grep | awk '{print $2}'`
if [[ "$1" == "stop" || "$1" == "restart" ]]; then
    if [[ "${pid}" != "" ]]; then
        echo "stop last running datasync, pid=${pid}"
        kill -9 ${pid}
        while [[ "${pid}" != "" ]]; do
            sleep 1
            pid=`ps -ef | grep "$CWD/datasync" | grep -v grep | awk '{print $2}'`
        done
    fi
    if [[ "$1" == "stop" ]]; then
        exit 0
    fi
elif [[ "$1" == "status" ]]; then
    if [[ "${pid}" == "" ]]; then
        echo "datasync is shutdown"
    else
        echo "datasync is running, pid=${pid}"
    fi
    exit 0
elif [[ "$1" == "help" ]]; then
    printusage
    exit 0
elif [[ "${pid}" != "" ]]; then
    echo "datasync is running, pid=${pid}"
    printusage
    exit 0
fi

#开始启动
nohup $CWD/datasync "$@" 1>/dev/null 2>${STDERROR} & 
echo "datasync is started"
printusage
