#!/bin/bash
#
#chkconfig: 2345 80 90
#for jar start stop
. /etc/init.d/functions
. /etc/profile
APPNAME=permission-service
PIDFILE=/var/run/${APPNAME}.pid
FILEPATH=/opt/${APPNAME}/target/${APPNAME}.jar
JAVA_OPTS="-Xms1024m -Xmx1024m"

JAVA_HOME=/usr/java/jdk1.8.0_92
JAVA=$JAVA_HOME/bin/java

start(){

    process_stat
    STAT=$?
    
    if [ $STAT -eq 0 ];then
        echo "$APPNAME is running"
        return $STAT
    elif [ $STAT -eq 1 ];then
        echo "$APPNAME is running,but pid file is incorrect!"
        return $STAT
    elif [ $STAT -eq 2 ];then
        echo "$APPNAME is running,but pid file is incorrect!"
        return $STAT
    elif [ $STAT -eq 3 ];then
        echo -n "Start $APPNAME: "
	nohup $JAVA -jar $JAVA_OPTS ${FILEPATH} >/dev/null 2>&1 &
	echo $! > ${PIDFILE}
	echo "[ok]"
    fi
}

stop(){

    process_stat
    STAT=$?

    if [ $STAT -eq 0 ];then
        echo  -n "Stop $APPNAME:"  
        killproc -p ${PIDFILE} -d 3 
		process_stat
        if [ $? -eq 3 ];then
		echo  "[OK]"
	fi
 
    elif [ $STAT -eq 1 ];then
        echo "can not stop $APPNAME process,the pid file is incorrect!"
        return $STAT
    elif [ $STAT -eq 2 ];then
        echo "can not stop $APPNAME process,the pid file is incorrect!"
        return $STAT
    elif [ $STAT -eq 3 ];then
        echo "$APPNAME is stopped"
        return 0
    fi

}

status(){  
    process_stat
    STAT=$?

    if [ $STAT -eq 0 ];then
        echo "$APPNAME is running"
        return $STAT
    elif [ $STAT -eq 1 ];then
        echo "$APPNAME is running,but pid file is incorrect!"
        return $STAT
    elif [ $STAT -eq 2 ];then
        echo "$APPNAME is running,but pid file is incorrect!"
        return $STAT
    elif [ $STAT -eq 3 ];then
        echo "$APPNAME is stopped"
        return $STAT
    fi
}

process_stat(){
    pid1=`ps -ef |grep ${APPNAME} |grep -v grep|grep java |awk -F" " '{print $2}'`
    pid2=`cat ${PIDFILE} 2>/dev/null`
    if [ -n "$pid1" ];then
        if [ -n "$pid2" ];then
            if [ "$pid1" = "$pid2" ];then
                return 0
            else
                return 1
            fi
        else
            return 2
        fi

    else
        #echo "$APPNAME is stopped"
        return 3
    fi
} 




case "$1" in  
start)  
  start  
  ;;  
stop)  
  stop  
  ;;  
restart)  
  stop  
  start  
  ;;
status)
  status
  ;;
*)  
  printf 'Usage: %s {start|stop|restart|status}\n' "$APPNAME"  
  exit 1  
  ;;  
esac