#!/bin/bash
#rd_hyc
# webapp执行脚本,启动参数为start|status|stop|restart|debug
#获取本地路径
# resolve links - $0 may be a softlink
PRG="$0"
while [ -h "$PRG" ]; do
  ls=`ls -ld "$PRG"`
  link=`expr "$ls" : '.*-> \(.*\)$'`
  if expr "$link" : '/.*' > /dev/null; then
    PRG="$link"
  else
    PRG=`dirname "$PRG"`/"$link"
  fi
done

# Get standard environment variables
PRGDIR=`dirname "$PRG"`

cd $PRGDIR
#设置初始参数
#source执行子级命令后继续执行父级命令，同时子级设置的环境变量会影响到父级的环境变量
source setenv.sh

appName="fileserver"
JPDA_ADDRESS=9800
JETTY_WEBAPP_PATH="../webapp"
JETTY_CONTEXT=fileserver
BOOTCLASS="kd.bos.service.webserver.JettyServer"

#检查java运行环境
if [ -x "$JAVA_HOME/bin/java" ]; then
    JAVA="$JAVA_HOME/bin/java"
else
    JAVA=`which java`
fi

if [ ! -x "$JAVA" ]; then
    echo "Could not find any executable java binary. Please install java in your PATH or set JAVA_HOME"
    exit 1
fi

#java运行参数
JAVA_OPTS="$JAVA_OPTS $JAVA_JMX_OPS -Dfile.encoding=UTF-8 -DappName=$appName -DJETTY_PORT=$JETTY_PORT -DJETTY_WEBAPP_PATH=$JETTY_WEBAPP_PATH -DJETTY_CONTEXT=$JETTY_CONTEXT "
DEBUG_OPTS=" -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=$JPDA_ADDRESS,server=y,suspend=n "

#获取jar列表
cd ../trd
TRD_JARS=`ls |grep .jar|awk '{print "../trd/"$0}'|tr "\n" ":"`
cd ../lib
LIB_JARS=`ls |grep .jar|awk '{print "../lib/"$0}'|tr "\n" ":"`
cd ../bin
echo `pwd`
rm -rf ../logs/*

#获得进程号
pidlist=`ps -ef|grep kd.bos.service.webserver.JettyServer|grep appName=$appName |grep -v "grep"|awk '{print $2}'`

#检查disk_url
checkDiskUrl(){
	echo "disk_url=$disk_url"
	if [ 0"$disk_url" = "0" ]; then
	  echo "Error: can not find disk_url in environment variable, please set it."
	  sleep 5
	  exit 1
	else
	#检查disk_url配置目录是否存在
		if [ ! -d "$disk_url" ]; then
			echo "Error: $disk_url does not exist, please create the directory."
			sleep 5
			exit 1
		fi
	fi
	#禁止配置如下目录为disk_url
	forbidArr=("/tmp" "/sys")
	for forbidStr in ${forbidArr[@]} 
	do
	   if [[ $disk_url = $forbidStr* ]];then
		echo "Error: disk_url can not config startwith ${forbidArr[@]}."
		sleep 5
		exit 1
	fi 
	done
	
	#检查disk_url是否挂盘，grep时前后加空格，防止关键字匹配误判
	grepDiskUrlStr=`cat /proc/self/mounts|grep " $disk_url "`
	echo "grepDiskUrlStr = $grepDiskUrlStr"
	if [ "$grepDiskUrlStr" =  "" ]; then
			echo "Error: The directory $disk_url does not mount disks."
			sleep 5
			exit 1
	fi
}

start()
{
  checkDiskUrl
  #重新获取一次,避免在restart时,出现pid值仍然存在的情况
  pidlist=`ps -ef|grep kd.bos.service.webserver.JettyServer|grep appName=$appName |grep -v "grep"|awk '{print $2}'`
  # Check the pid
  if [ "$pidlist" = "" ] ; then
    echo "$JAVA $JAVA_OPTS  -classpath  ../conf/:$TRD_JARS:$LIB_JARS $BOOTCLASS >../logs/fileserver.log 2>&1 &" 
    echo -n "Starting webapp: "
    nohup $JAVA $JAVA_OPTS -classpath  ../conf/:$TRD_JARS:$LIB_JARS $BOOTCLASS > ../logs/fileserver.log  2>&1 &
    echo "$appName start successfully!!"
  else
    echo "$appName is still running,please confirm and use stop|restart!"
  fi
}

debug()
{
  checkDiskUrl
  #重新获取一次,避免在restart时,出现pid值仍然存在的情况
  pidlist=`ps -ef|grep kd.bos.service.webserver.JettyServer|grep appName=$appName |grep "Xdebug"|grep -v "grep"|awk '{print $2}'`
  # Check the pid
  if [ "$pidlist" = "" ] ; then
    echo -n "Starting $appName debug mode: "
    nohup $JAVA $JAVA_OPTS $DEBUG_OPTS -classpath  ../conf/:$TRD_JARS:$LIB_JARS $BOOTCLASS > ./fileserver.log  2>&1 &
    echo "$appName debug start successfully!!"
  else
    echo "$appName is still running,please confirm and use stop|restart!"
  fi
}

stop()
{
  echo -n $"Stopping webapp: "
  if [ "$pidlist" = "" ];then
      echo "no $appName pid alive"
  else
      for pid in ${pidlist}
      {
         kill -9 $pid
         echo "KILL $pid:"
      }
      echo "$appName stop success"
   fi
}

status () {
       if [ "$pidlist" = "" ] ; then
          echo "$appName is stoped! "
       else
          echo "$appName is running! "
       fi
}

#此处有个问题,之前运行为正常start模式,重启后,也会变成debug模式
#已修改,不要使用pid,换为dpid,应该是因为pid变量在上面有使用:(,那不是局部变量么?
restart () {
        checkDiskUrl
        dpid=`ps -ef|grep kd.bos.service.webserver.JettyServer|grep appName=$appName |grep "Xdebug"|grep -v "grep"|awk '{print $2}'`
        stop
        #如果进程不存在,正常启动
        if [ "$pidlist" = "" ];then
            start
        #进程存在,则判断原来运行模式
        else
            #为空表示非debug模式
            if [ "$dpid" = "" ] ; then
              start
            else
               echo "$dpid into debug.........."
               debug
            fi         
        fi
}

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  debug)
    debug
    ;;  
  restart|reload|force-reload)
    restart
    ;;
  status)
    status
    ;;
  *)
    echo "Usage: $0 {start|stop|status|restart|debug}"
    RETVAL=1
esac

exit $RETVAL
