#!/bin/bash

# for dev
#    bin/start-server.sh ../app-web/target
set -e

Green='\033[0;32m'        # Green
Yellow='\033[0;33m'       # Yellow
Red='\033[0;31m'          # Red
Blue='\033[0;34m'         # Blue
Purple='\033[0;35m'       # Purple
Cyan='\033[0;36m'         # Cyan
White='\033[0;37m'        # White
NC='\033[0m'              # No Color

basePath=$(cd `dirname $0`; pwd)
cd $basePath
echo -e "${Purple}[IBI] Working path = $basePath${NC}"
# dt=`date +"%Y-%m-%d"`

pidCmd="ps -ef | grep java | grep "${basePath}" | grep -v grep | awk '{print \$2}'"
Server=$(eval $pidCmd)

# 定义检查配置项的函数
check_config() {
    local key="$1"
    local file="config/application.properties"

    # 使用 grep 检查配置是否存在且未被注释
    if grep -qE "^\s*${key}\s*=" "$file"; then
        echo 1
    else
        echo 0
    fi
}

hasNodeService=$(check_config "nodejs.koa2.base-url")
# 确保脚本继续执行，无论函数返回什么
echo "hasNodeService : $hasNodeService"


ibi_stop() {
   if [[ $Server != "" && $Server -gt 0 ]]; then
        # echo "============================================="
        echo -e " ${Red}Stopping IBI Service.....${NC} "
        kill -9 $Server
        echo -e " ${Green}Stopped${NC} "
        # echo "============================================="
   else
      echo "============================================="
      echo -e "  IBI Server is ${Red} NOT RUNNING${NC} "
      echo "============================================="
   fi

   if [[ $hasNodeService -eq 1 ]]; then
       # 定义应用的名字或路径
       APP_NAME="koa-api/bundle.js"
       koaPidCmd="ps -ef | grep "${basePath}" | grep ${APP_NAME} | grep -v grep | awk '{print \$2}'"
       koaPid=$(eval $koaPidCmd)

       if [[ $koaPid != "" && $koaPid -gt 0 ]]; then
            # echo "============================================="
            echo -e " ${Red}Stopping IBI Koa-API Service.....${NC} "
            kill -9 $koaPid
            echo -e " ${Green}Stopped${NC} "
            # echo "============================================="
       else
          echo ""
          echo "============================================="
          echo -e " IBI Koa-API Server is ${Red} NOT RUNNING${NC} "
          echo "============================================="
       fi
   fi


}

ibi_stop