#!/bin/bash
cd `dirname $0`

# Your jar package
APP_NAME=myapp.jar
# Optional
JVM="-Dfile.encoding=utf-8 -server -Xmx1g"
ARGS="--spring.profiles.active=dev --server.port=8080"
LOG_FILE=running.log

help(){
    echo "Usage: [start|stop|restart|status]"
    exit 1
}

is_exist(){
  pid=`ps -ef|grep $APP_NAME|grep -v grep|awk '{print $2}'`
  # if progress is exist then return 1,else return 0
  if [ -z "${pid}" ]; then
    return 1
  else
    return 0
  fi
}

start(){
  is_exist
  if [ $? -eq 0 ]; then
    echo "${APP_NAME} is already running. pid=${pid}"
  else
    nohup java ${JVM} -jar ./${APP_NAME} ${ARGS} > ${LOG_FILE} 2>&1 &
    echo "${APP_NAME} is start successfully, use 'log' option to print more info."
  fi
}

stop(){
  is_exist
  if [ $? -eq "0" ]; then
    kill -9 $pid
    echo "${APP_NAME} is stoped"
  else
    echo "${APP_NAME} is not running"
  fi
}

status(){
  is_exist
  if [ $? -eq "0" ]; then
    echo "${APP_NAME} is running. Pid is ${pid}"
  else
    echo "${APP_NAME} is NOT running."
  fi
}

restart(){
  stop
  sleep 2
  start
}

log(){
  tail -n 100 -f server.log
}

case "$1" in
  "start")
    start
    ;;
  "stop")
    stop
    ;;
  "status")
    status
    ;;
  "restart")
    restart
    ;;
  "log")
    log
    ;;
  *)
    help
    ;;
esac
