#!/bin/sh
# ./ry.sh start 启动 stop 停止 restart 重启 status 状态

# 定义JAR包所在目录
APP_HOME=/home/yjly/www/API/ruoyi
AppName=ruoyi-admin.jar
# JAR包完整路径
JAR_PATH=$APP_HOME/$AppName

# JVM参数
JVM_OPTS="-Dname=$AppName  -Duser.timezone=Asia/Shanghai -Xms512m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -XX:+PrintGCDateStamps  -XX:+PrintGCDetails -XX:NewRatio=1 -XX:SurvivorRatio=30 -XX:+UseParallelGC -XX:+UseParallelOldGC"

# 日志文件路径
LOG_PATH=$APP_HOME/logs/$AppName.log

if [ "$1" = "" ];
then
    echo -e "\033[0;31m 未输入操作名 \033[0m  \033[0;34m {start|stop|restart|status} \033[0m"
    exit 1
fi

# 检查JAR包是否存在
if [ ! -f "$JAR_PATH" ];
then
    echo -e "\033[0;31m 应用JAR包不存在: $JAR_PATH \033[0m"
    exit 1
fi

function start()
{
    PID=`ps -ef |grep java|grep $AppName|grep -v grep|awk '{print $2}'`

	if [ x"$PID" != x"" ]; then
	    echo "$AppName is running..."
	else
		# 进入应用目录
		cd $APP_HOME
		# 创建logs目录如果不存在
		if [ ! -d "$APP_HOME/logs" ]; then
			mkdir -p $APP_HOME/logs
		fi
		nohup java $JVM_OPTS -jar $JAR_PATH > /dev/null 2>&1 &
		echo "Start $AppName success..."
		# 显示启动日志
		sleep 2
		echo "查看启动日志: tail -f $LOG_PATH"
	fi
}

function stop()
{
    echo "Stop $AppName"

	PID=""
	query(){
		PID=`ps -ef |grep java|grep $AppName|grep -v grep|awk '{print $2}'`
	}

	query
	if [ x"$PID" != x"" ]; then
		kill -TERM $PID
		echo "$AppName (pid:$PID) exiting..."
		while [ x"$PID" != x"" ]
		do
			sleep 1
			query
		done
		echo "$AppName exited."
	else
		echo "$AppName already stopped."
	fi
}

function restart()
{
    stop
    sleep 2
    start
}

function status()
{
    PID=`ps -ef |grep java|grep $AppName|grep -v grep|wc -l`
    if [ $PID != 0 ];then
        echo "$AppName is running..."
        # 显示运行进程详情
        ps -ef |grep java|grep $AppName|grep -v grep
    else
        echo "$AppName is not running..."
    fi
}

# 新增查看日志函数
function log()
{
    if [ ! -f "$LOG_PATH" ]; then
        echo "日志文件不存在: $LOG_PATH"
    else
        tail -f $LOG_PATH
    fi
}

# 新增查看端口函数
function port()
{
    PID=`ps -ef |grep java|grep $AppName|grep -v grep|awk '{print $2}'`
    if [ x"$PID" != x"" ]; then
        echo "应用进程ID: $PID"
        # 获取端口号
        netstat -tlnp 2>/dev/null | grep $PID
    else
        echo "$AppName 未运行"
    fi
}

# 新增备份函数
function backup()
{
    DATE=`date +%Y%m%d%H%M%S`
    BACKUP_DIR="$APP_HOME/backup"
    if [ ! -d "$BACKUP_DIR" ]; then
        mkdir -p $BACKUP_DIR
    fi
    BACKUP_FILE="$BACKUP_DIR/$AppName.$DATE"
    cp $JAR_PATH $BACKUP_FILE
    echo "已备份到: $BACKUP_FILE"
}

case $1 in
    start)
    start;;
    stop)
    stop;;
    restart)
    restart;;
    status)
    status;;
    log)
    log;;
    port)
    port;;
    backup)
    backup;;
    *)
    echo -e "\033[0;31m 无效的操作名 \033[0m"
    echo "用法: $0 {start|stop|restart|status|log|port|backup}"
    exit 1
esac