#!/bin/sh

#APP_HOME=/tcs/itcs/bin
#LOG_HOME=/tcs/itcs/logs
APP_HOME=/home/openvalue/bin
LOG_HOME=/home/openvalue/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_JAR="$APP_HOME/$GITS_APP-0.0.1.jar"
ETLP_JAR="$APP_HOME/$ETLP_APP-0.0.1.jar"
COMM_JAR="$APP_HOME/$COMM_APP-0.0.1.jar"
TODP_JAR="$APP_HOME/$TODP_APP-0.0.1.jar"
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"

start_program() {
    JAR_FILE=$1
    PID_FILE=$2
    PROGRAM_NAME=$3

    if [ -f $PID_FILE ]; then
        PID=$(cat $PID_FILE)
        if ps -p $PID > /dev/null 2>&1; then
            echo "    >> $PROGRAM_NAME is already running."
            exit 1
        else
            rm $PID_FILE
        fi
    fi

    JAVA_OPT="-server"
    #JAVA_OPT="$JAVA_OPT -Xlog:gc*:file=${LOG_HOME}/${PROGRAM_NAME}/${PROGRAM_NAME}.gc.log"
    java $JAVA_OPT -jar $JAR_FILE &
    echo $! > $PID_FILE
    echo "    >> $PROGRAM_NAME started with PID $(cat $PID_FILE)"
}

case $1 in
  ggits)
    start_program $GITS_JAR $GITS_PID $GITS_APP
    ;;
  etlp)
    start_program $ETLP_JAR $ETLP_PID $ETLP_APP
    ;;
  comm)
    start_program $COMM_JAR $COMM_PID $COMM_APP
    ;;
  todp)
    start_program $TODP_JAR $TODP_PID $TODP_APP
    ;;
  all)
    start_program $GITS_JAR $GITS_PID $GITS_APP
    start_program $ETLP_JAR $ETLP_PID $ETLP_APP
    start_program $COMM_JAR $COMM_PID $COMM_APP
    start_program $TODP_JAR $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
