#!/bin/sh
# java 环境 shell脚本有可能获取不到指定的java
JAVA_HOME=/usr/local/jdk1.8.0_72/bin

## 服务相关参数
APP_NAME=data-center-1.0.0-SNAPSHOT
SERVICE_DIR=/usr/local/tomcat/jars/datacenter/
JAR_NAME="$APP_NAME.jar"
PID_FILE="$SERVICE_DIR/$APP_NAME.pid"
SERVER_PORT=14501
CURRENT_LOG="$SERVICE_DIR/logs/out.log"
OLD_LOG_DATE="$SERVICE_DIR/logs/out_$(date +%Y-%m-%d-%H-%M-%S).log"

# 查看程序资
function show() {
  MSG=$(ps aux | grep "$APP_NAME" | grep -v grep | awk '{ print "CPU: " $3 "%, Memory: " $4 "%, Start Time: " $9 }')
  echo "$MSG"
}

# Debug模式启动
function debug() {
  if [ -f "$CURRENT_LOG" ]; then
    echo "Found an old log file, backing it up."
    mv "$CURRENT_LOG" "$OLD_LOG_DATE"
  fi
  nohup "$JAVA_HOME/java" -XX:+UseG1GC -Xms1024m -Xmx1024m -Dfile.encoding=UTF-8 -jar "$JAR_NAME" --server.port=$SERVER_PORT --server.tomcat.accesslog.directory="$SERVICE_DIR/logs/accessLogs/" > "$CURRENT_LOG" 2>&1 &
  echo $! > "$PID_FILE"
  #echo "Started $APP_NAME successfully. Current log file: $CURRENT_LOG. Process ID: $(cat "$PID_FILE")"
}

# 正常启动
function start() {
  nohup "$JAVA_HOME/java" -XX:+UseG1GC -Xms1024m -Xmx1024m -jar "$JAR_NAME" --server.tomcat.accesslog.directory="$SERVICE_DIR/logs/" > /dev/null 2>&1 &
  echo $! > "$PID_FILE"
  echo "Started $APP_NAME successfully."
}

# 停止服务
function stop() {
  PORT_ID=$(ps -ef | grep -w "$JAR_NAME" | grep -v grep | awk '{print $2}')
  echo "Port ID: $PORT_ID"
  if [ -z "$PORT_ID" ]; then
    echo "The $APP_NAME process does not exist or has already stopped."
  else
    kill $(cat "$PID_FILE")
    kill -9 $PORT_ID
    rm -f "$PID_FILE"
    echo "Stopped $APP_NAME successfully."
  fi
}

# 删除两个月之前的out文件
function clean_old_logs() {
  find "$SERVICE_DIR/logs/" -type f -name "out_*" -mtime +30 -exec rm -f {} \;
  echo "Old logs older than 1 months have been deleted."
}

# 检测用户输入参数并执行相应函数
cd "$SERVICE_DIR"
case "$1" in
  start)
    start
    ;;
  clean)
    clean_old_logs
    ;;
  stop)
    stop
    ;;
  debug)
    debug
    ;;
  restart)
    stop
    sleep 5
    clean_old_logs
    sleep 2
    debug
    ;;
  show)
    show
    ;;
  *)
    echo "Usage: $0 {start|stop|debug|restart|show|clean}"
    ;;
esac

exit 0
