#!/bin/bash

# Author: wuyq
# Date: 2021-12-30 14:30
# Desc: start jar
#

# error code
# 1: missing parameter
# 2: not a jar file
# 3: start jar file failed

TIMEOUT=180  # 3 minutes timeout
projectpath=$(dirname $0)
cd $projectpath
appName=`ls -t |grep ".*\.jar$" |head -n1`
jarfile=$appName

function echo_error() {
    printf "[ \033[31mERROR $1\033[0m ] $2\n"
}

function main() {

        echo "检查jar包开始"
        # check file type

        local extension=${jarfile##*.}
        if [[ $extension != jar ]];then
                echo_error 2 "not a jar file"
                exit 2
        fi
        echo "检查jar包成功"
        echo "***********************************"
        echo "停止进程 $jarfile 开始"
        # check process is running
        local pid=$(ps -ef|grep -E "$jarfile" | grep -v grep |awk '{print $2}')
        #if [[ "$pid" != "" ]];then
        #       ps -ef|grep -E "\-jar $jarfile" | grep -v grep
        #       printf "[ \033[33mWARNING\033[0m ] a process $pid of $jarfile is running.\n"
        #       printf "    the $0 $jarfile is canceled or rerun restart.sh $jarfile\n"
        #       exit 0
        #fi
        if [ -n "$pid" ]; then
          echo "kill -9 的pid:" $pid
          kill -9  $pid
        fi
        echo "停止进程结束"

        echo "start jar -------------->"
        # start jar file
        source /etc/profile
 #h /data/project/market/start.sh
 #cd /data/project/market
 cd $projectpath
#nohup java -Xms256m -Xmx512m -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5006 -jar market-rest.jar --spring.profiles.active=prod >/dev/null 2>&1 &
#nohup java -XX:+UseConcMarkSweepGC -XX:+HeapDumpOnOutOfMemoryError -Xms1536m -Xmx1536m -jar $jarfile   >/dev/null 2>&1 &
#nohup java -XX:+HeapDumpOnOutOfMemoryError -Xms2048m -Xmx4096m -Xmn2048m  -Dloader.path="lib/" -jar $jarfile >/dev/null 2>&1 &
#nohup java -jar -XX:+UseG1GC -XX:+HeapDumpOnOutOfMemoryError -Xms1024m -Xmx1024m $jarfile --spring.profiles.active=pro > /dev/null 2>&1 &
 #nohup java -jar -XX:+UseG1GC -XX:+HeapDumpOnOutOfMemoryError -Xms1024m -Xmx1024m -Dlog4j2.formatMsgNoLookups=true $jarfile --spring.profiles.active=ddy > /dev/null 2>&1 &
 #nohup java -Dloader.path=lib/ -Xms1024m -Xmx1024m -Xmn1024m  -jar communityData.jar >/dev/null &
 nohup java -XX:+HeapDumpOnOutOfMemoryError -Xms1024m -Xmx1024m  -Xdebug -Xrunjdwp:transport=dt_socket,address=5033,server=y,suspend=n -jar $jarfile --spring.profiles.active=pro  > $projectpath/$jarfile.out.log 2>&1 &
if [ $? -ne 0 ]; then
  echo "start service error "
else
  echo "start service success"
  echo "sleep 10s , then ps -ef|grep java |grep $jarfile "
  sleep 10
fi
count=`ps -ef|grep java |grep $jarfile`
echo $count
}


main $*

