#!/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)

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

ibi_start() {

    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 " [IBI] Server is starting, pid=$Server"
      echo -e " ${Yellow}auto check log command ====> tail -f ${basePath}/logs/cboard.log${NC}"
      echo "=========================================="
      tail -f ${basePath}/logs/cboard.log
    else
      eval ${javaCmd}
    fi
}

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
}

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


case $1 in
    start )
        ibi_start
    ;;

    stop )
        ibi_stop
    ;;

    status )
        ibi_status
     ;;

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



