#!/bin/sh

APP_HOME=/tcs/itcs/bin
LOG_HOME=/tcs/itcs/logs

APP_NAME="-server-0.0.1.jar"
GITS_APP="ggits-comm-server"
ETLP_APP="ggits-etlp-server"
COMM_APP="sig-comm-server"
TODP_APP="sig-todp-server"
GITS_PID="$APP_HOME/conf/$GITS_APP.pid"
ETLP_PID="$APP_HOME/conf/$ETLP_APP.pid"
COMM_PID="$APP_HOME/conf/$COMM_APP.pid"
TODP_PID="$APP_HOME/conf/$TODP_APP.pid"

stop_program() {
    PID_FILE=$1
    PROGRAM_NAME=$2

    if [ ! -z $PID_FILE ]; then
        if [ -f $PID_FILE ]; then
            PID=$(cat $PID_FILE)
            if ps -p $PID > /dev/null 2>&1; then
                kill -15 $PID
                echo "    >> $PROGRAM_NAME, Killed process $PID"

                for i in {0..12}
                do
                  sleep 1
                  if [ -f "$PID_FILE" ]; then
                    echo "    >> $PROGRAM_NAME stopping.........."
                  else
                    echo "    >> $PROGRAM_NAME stopped.........."
                    break
                    #exit
                  fi
                done

                if [ -f "$PID_FILE" ]; then
                    kill -9 $PID
                    sleep 1
                    rm $PID_FILE
                fi
            else
                echo "No process found with PID $(cat $PID_FILE)"
                rm $PID_FILE
            fi
        else
            echo "    >> $PROGRAM_NAME is not running...."
            ps -eaf | grep $PROGRAM_NAME | grep -v grep |grep -v tail | wc -l
            ps -eaf | grep $PROGRAM_NAME | grep -v grep |grep -v tail
            #exit
        fi
    fi
}

case $1 in
  ggits)
    stop_program $GITS_PID $GITS_APP
    ;;
  etlp)
    stop_program $ETLP_PID $ETLP_APP
    ;;
  comm)
    stop_program $COMM_PID $COMM_APP
    ;;
  todp)
    stop_program $TODP_PID $TODP_APP
    ;;
  all)
    stop_program $GITS_PID $GITS_APP
    stop_program $ETLP_PID $ETLP_APP
    stop_program $COMM_PID $COMM_APP
    stop_program $TODP_PID $TODP_APP
    ;;
  *)
    echo "Usage: $0 {ggits|etlp|comm|todp|all}"
    exit 1
    ;;
esac

sleep 1

ps -eaf | grep java | grep jar | grep $APP_NAME | grep -v grep | grep -v tail | grep -v kafka | grep -v vi | wc -l
sleep 1
ps -eaf | grep java | grep jar | grep $APP_NAME | grep -v grep | grep -v tail | grep -v kafka | grep -v vi
