#!/bin/bash

APP_NAME='agent.jar'
CMD='java -jar agent.jar -jnlpUrl http://jk.ywsco.cn:8088/computer/yunlianshen/jenkins-agent.jnlp -secret 208d94afcd238bc08874070ba2eadbe00717e62dc4bdfd3745a5ef54ef6c6d2d -workDir "/data/jenkins_agent"'

usage() {
  echo "Usage: $0 [start|stop|restart|status]"
  exit 1
}

is_exist(){
  pid=$(ps -ef|grep $APP_NAME|grep -v grep| grep -v 'deploy.sh'|awk '{print $2}' )
  #如果不存在返回1，存在返回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 ./xjar $JAVA_HOME/java -Djava.io.tmpdir=$TMP_DIR  $OPTIONS  -jar $APP_NAME >  /dev/null 2>&1 --server.port=$SERVICE_PORT --spring.config.location=$SPRING_CONFIG_LOCATION &
    nohup $CMD &
  fi
}

stop(){
  is_exist
  if [ $? -eq "0" ]; then
     echo  "kill $pid ..."
     kill  $pid
  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 2s
  start
}

case "$1" in
  "start")
    start
    ;;
  "stop")
    stop
    ;;
  "status")
    status
    ;;
  "restart")
    restart
    ;;
  *)
    usage
    ;;
esac

