#!/bin/sh

SERVER_IP=192.168.77.22
SERVER_PORT=9090

NK_HOME_DEFAULT=/home/northking
PRODUCTION_NAME=cctp
APP_NAME=atu-script-case
APP_VERSION=3.0-SNAPSHOT
JAR_FILE=${APP_NAME}-${APP_VERSION}.ms.jar
APP_PORT=8810

JAVA_OPTIONS="-Xmx1024M -Dfile.encoding=UTF-8 -Dloader.path=.,lib"
PORT_OPTIONS="--server.port=${APP_PORT}"

if [ 0"$NK_HOME" = "0" ]; then
    echo "NK_HOME unset, use default value : $NK_HOME_DEFAULT"
    NK_HOME=${NK_HOME_DEFAULT}
fi


PID=$(ps aux | grep ${JAR_FILE} | grep -v grep | awk '{print $2}' )

check_if_process_is_running() {
 if [ "$PID" = "" ]; then
 return 1
 fi
 ps -p $PID | grep "java"
 return $?
}

install_upgrade() {
  upgrade_url="http://${SERVER_IP}:${SERVER_PORT}/${PRODUCTION_NAME}/${APP_VERSION}/${APP_NAME}"
  rm -rf ${JAR_FILE}
  wget ${upgrade_url}/${JAR_FILE}

  rm -rf install.list
  wget ${upgrade_url}/install.list

  mkdir -p config
  mkdir -p lib


  cd config
  rm -rf application.yml
  wget ${upgrade_url}/config/application.yml

  cd ../lib
  rm -rf *
  for filename in `cat ../install.list`
  do
    echo ${filename}
    wget http://${SERVER_IP}:${SERVER_PORT}/lib/${filename}
  done

  cd ..
}



case "$1" in
  upgrade)
    $0 stop
    install_upgrade
  ;;
  status)
   if check_if_process_is_running
   then
     echo -e "\033[32m $APP_NAME is running \033[0m"
   else
     echo -e "\033[32m $APP_NAME not running \033[0m"
   fi
  ;;
  stop)
    if ! check_if_process_is_running
    then
      echo -e "\033[32m $APP_NAME already stopped \033[0m"
      exit 0
    fi
    kill -9 $PID
      echo -e "\033[32m $APP_NAME already stopped \033[0m"
  ;;
  start)
    if [ "$PID" != "" ] && check_if_process_is_running
    then
      echo -e "\033[32m $APP_NAME already running \033[0m"
      exit 1
    fi
    nohup java -jar ${JAVA_OPTIONS} ${JAR_FILE} ${PORT_OPTIONS} > /dev/null 2>&1 &
    echo -ne "\033[32m Starting \033[0m"

    if check_if_process_is_running
    then
      echo -e "\033[32m $APP_NAME fail \033[0m"
    else
      echo -e "\033[32m $APP_NAME started \033[0m"
    fi
  ;;
  debug)
    java -jar ${JAVA_OPTIONS} ${JAR_FILE} ${PORT_OPTIONS}
  ;;
  restart)
  $0 stop
  if [ $? = 1 ]
  then
    exit 1
  fi
  $0 start
  ;;
 *)
 echo "Usage: $0 {start|stop|restart|status|upgrade|debug}"
 exit 1
esac


exit 0
