#!/bin/bash

# 牛只数据管理后端启动脚本
# 使用方法: ./start.sh [start|stop|restart]

APP_NAME="cattletends"
JAR_NAME="cattletends-1.0.0.jar"
APP_PORT=12240
JAVA_OPTS="-Xms512m -Xmx1024m"
SPRING_PROFILE="prod"
LOG_FILE="log.out"
PID_FILE="pid.${APP_NAME}"

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"


# 检查jar文件是否存在
if [ ! -f "$JAR_PATH" ]; then
    echo "错误: 找不到jar文件: $JAR_PATH"
    echo "请先执行 mvn clean package 打包项目"
    exit 1
fi

# 停止应用
function stopApp() {
    echo "正在停止应用: $APP_NAME"
    
    # 查找进程
    PID=$(ps -ef | grep java | grep "$JAR_NAME" | grep -v grep | awk '{print $2}')
    
    if [ -n "$PID" ]; then
        echo "找到进程 PID: $PID"
        kill -15 $PID
        
        # 等待进程结束，最多等待10秒
        for i in {1..10}; do
            if ! ps -p $PID > /dev/null 2>&1; then
                echo "应用已停止"
                rm -f $PID_FILE
                return 0
            fi
            sleep 1
        done
        
        # 如果还在运行，强制杀死
        if ps -p $PID > /dev/null 2>&1; then
            echo "强制停止进程..."
            kill -9 $PID
            rm -f $PID_FILE
        fi
    else
        echo "应用未运行"
        rm -f $PID_FILE
    fi
}

# 启动应用
function startApp() {
    echo "正在启动应用: $APP_NAME"
    
    # 检查是否已经运行
    PID=$(ps -ef | grep java | grep "$JAR_NAME" | grep -v grep | awk '{print $2}')
    if [ -n "$PID" ]; then
        echo "应用已经在运行中，PID: $PID"
        return 1
    fi
    
    # 启动应用
    nohup java $JAVA_OPTS \
        -Dspring.profiles.active=$SPRING_PROFILE \
        -Dserver.port=$APP_PORT \
        -jar "$JAR_PATH" > "$LOG_FILE" 2>&1 &
    
    # 等待启动
    sleep 3s
    
    # 检查进程
    PID=$(ps -ef | grep java | grep "$JAR_NAME" | grep -v grep | awk '{print $2}')
    
    if [ -n "$PID" ]; then
        echo "应用启动成功，PID: $PID"
        echo $PID > $PID_FILE
        echo "日志文件: $LOG_FILE"
        echo "查看日志: tail -f $LOG_FILE"
        return 0
    else
        echo "应用启动失败，请查看日志: $LOG_FILE"
        return 1
    fi
}

# 重启应用
function restartApp() {
    echo "========== 重启应用: $APP_NAME =========="
    stopApp
    sleep 2s
    startApp
}

# 查看状态
function statusApp() {
    PID=$(ps -ef | grep java | grep "$JAR_NAME" | grep -v grep | awk '{print $2}')
    if [ -n "$PID" ]; then
        echo "应用运行中，PID: $PID"
        echo "端口: $APP_PORT"
        echo "日志: $LOG_FILE"
    else
        echo "应用未运行"
    fi
}

# 主逻辑
case "$1" in
    start)
        startApp
        ;;
    stop)
        stopApp
        ;;
    restart)
        restartApp
        ;;
    status)
        statusApp
        ;;
    *)
        echo "使用方法: $0 {start|stop|restart|status}"
        echo ""
        echo "参数说明:"
        echo "  start   - 启动应用"
        echo "  stop    - 停止应用"
        echo "  restart - 重启应用"
        echo "  status  - 查看应用状态"
        exit 1
        ;;
esac

exit $?

