#!/bin/bash
tbasepath=$(cd `dirname $0`; pwd -P)
version=$(cat $tbasepath/version)
cd $tbasepath/..
basepath=$tbasepath/..
spid=$tbasepath/commandAutoProxy.pid

start(){
    pid=$(currentPId)
    if [ "$pid" = "" ]; then
        nohup  java -classpath "$basepath/$version/lib/*:."  kd.bos.olap.autoProxys.OlapAutoProxyMain >> $tbasepath/autoProxy.log   2>&1 & echo $! >  $spid
        sleep 1
        tPid=$(currentPId)
        if [ "$tPid" = "" ]; then
            echo "error, olap auto proxy start failed."
        else
            echo "olap auto proxy had been started."
        fi
    else
       echo "please don't repeat start, olap auto proxy had been started."
    fi
}

# 检查OLAP自动代理是否停止
check_olap(){
    needPrint=true
    while true
    do
        exist_flg=$(ps --no-headers -fp $1 |wc -l)
        if [ $exist_flg -eq 0 ]; then
            rm -rf $spid
            break
        else
            if  $needPrint ; then
                echo "please waiting olap auto proxy stopped..."
                needPrint=false
            fi
	        sleep 1
        fi
    done
}

stop(){
    pid=$(currentPId)
    ps_pid=$(ps -ef|grep java|grep OlapAutoProxyMain|grep "$tbasepath"| grep -v grep| tr -s ' '| cut -d ' ' -f 2)
    if [ "$pid" != "$ps_pid" ]; then 
        echo "OLAP auto proxy process PID:"
        ps -ef|grep java|grep olap|grep "$tbasepath"| grep -v grep
#        echo "$(ps --no-headers -fp $pid)"
        for i in $ps_pid ;do
            echo "$i will be stop."
            kill -15 $i
            check_olap $i
        done
        pid=""
    fi
    
    if [ "$pid" != "" ]; then
    	echo "$pid will be stop."
        kill -15 $pid
        check_olap $pid
    fi
    
    echo "olap auto proxy had been stopped."
}

status(){
    pid=$(currentPId)
    if [ "$pid" = "" ]; then
        #echo "olap auto proxy had been stopped."
		echo 0
    else
        #echo "olap auto proxy status is started."
		echo 1
    fi
}

restart(){
    stop
    start
}

currentPId(){
    if [ -e $spid ];then
        pid=`cat $spid`
        tpid=`ps --no-headers -fp $pid|grep java|wc -l`
		if [ $tpid -ne 1 ];then
		   pid=""
		fi
    else
        pid=""
	fi
    echo $pid
}

case $1 in
start)
       start
       ;;
stop)
       stop
       ;;
restart)
        restart
        ;;
status)
       status
       ;;
*)
        echo "Usage: $0  start | stop | restart | status ."
        ;;
esac
