#!/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 ibi.jar | 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"

KOA_APP_NAME="koa-api/bundle.js"
koaPidCmd="ps -ef | grep "${basePath}" | grep ${KOA_APP_NAME} | grep -v grep | awk '{print \$2}'"
# echo ${koaPidCmd}
koaPid=$(eval $koaPidCmd)

export JAVA_OPTS="$JAVA_OPTS -Dloader.path=${basePath},${basePath}/config"

ibi_start() {

    # 定义日志文件路径
    LOG_DIR="logs"
    # 确保日志目录存在
    mkdir -p "${LOG_DIR}"

    if [[ $Server != "" && $Server -gt 0 ]]; then
      echo "=================================================="
      echo -e "[IBI] Server is already ${Green}RUNNING${NC} at pid: ${Server} "
      echo "=================================================="
      exit
    fi

    #java $JAVA_OPTS -jar ibi.jar
    javaCmd="java $JAVA_OPTS -jar ibi.jar"
    echo -e "${Yellow}[IBI] ${javaCmd}${NC}"
    eval nohup ${javaCmd} > /dev/null 2>&1 "&"

    Server=$(eval $pidCmd)
    if [[ $Server != "" &&  $Server -gt 0 ]]; then
      echo "=========================================="
      echo -e " ${Green} [IBI] Server is starting, pid=$Server"
      echo -e " ${Yellow} Check log command ====> tail -f ${basePath}/${LOG_DIR}/cboard.log${NC}"
      echo "=========================================="
      # tail -f ${basePath}/logs/cboard.log
    else
      eval ${javaCmd}
    fi

    if [[ $hasNodeService -eq 1 ]]; then
        echo "=========================================="
        echo "Start IBI KOA Service"

        LOG_FILE="${LOG_DIR}/koa-api-$(date +%Y-%m-%d).log"

        # 如果进程存在，终止它
        if [ -n "$koaPid" ]; then
            echo "Stopping existing ${KOA_APP_NAME} process with PID $koaPid"
            kill $koaPid
            sleep 1
        else
            echo "No existing koa-api process found."
        fi
        # 启动应用并将日志写入带有日期的文件中
        echo "Starting new ${KOA_APP_NAME} process..."
        node ${basePath}/$KOA_APP_NAME >> ${LOG_DIR}/koa-api.log 2>&1 &

        koa_stop
        koa_status
    else
        echo ""
    fi

}

koa_stop() {
  # 如果进程存在，终止它
  if [ -n "$koaPid" ]; then
      echo "Stopping existing ${KOA_APP_NAME} process with PID $koaPid"
      kill $koaPid
      sleep 1
  else
      echo "No existing koa-api process found."
  fi
}

koa_status() {
  # 检查koa启动情况
  koaPid=$(eval $koaPidCmd)
  if [[ $koaPid != "" &&  $koaPid -gt 0 ]]; then
     echo "=========================================="
     echo -e " ${Green} [IBI] KOA-API Server is started at pid=$koaPid ${NC}"
  else
     echo -e " ${Red} [IBI] KOA-API Server start failure, check log at ${LOG_DIR}/koa-api.log ${NC}"
  fi
  echo "=========================================="
}

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

ibi_status() {
    if [[ $Server != "" && $Server -gt 0 ]]; then
        # echo "==================================="
        echo -e " Server is [ ${Green}RUNNING${NC} ] at pid: $Server "
        # echo "==================================="
    else
        # echo "====================================="
        echo -e " Server is [ ${Red}NOT RUNNING${NC} ]"
        # echo "====================================="
    fi
    koa_status
}

action=${1:-start}

case $action in
    start )
        ibi_start
    ;;

    stop )
        ibi_stop
    ;;

    status )
        ibi_status
     ;;

    * )
        echo -e "${Yellow}Usage: start-server.sh (start|stop|status)${NC}"
esac



