#!/bin/bash

# 部署配置
SERVER_HOST="192.168.0.95"
SERVER_USER="root"
SERVER_PASSWORD="aiotagro"
DEPLOY_DIR="/data/java/aiotagro"
JAR_FILE="aagro-server/target/aagro-server.jar"
APP_NAME="aagro-server"

echo "开始部署到服务器 ${SERVER_HOST}..."

# 1. 创建部署目录
echo "1. 创建部署目录..."
sshpass -p "${SERVER_PASSWORD}" ssh -o StrictHostKeyChecking=no ${SERVER_USER}@${SERVER_HOST} "mkdir -p ${DEPLOY_DIR}/config ${DEPLOY_DIR}/logs"

# 2. 上传jar文件
echo "2. 上传jar文件..."
sshpass -p "${SERVER_PASSWORD}" scp -o StrictHostKeyChecking=no ${JAR_FILE} ${SERVER_USER}@${SERVER_HOST}:${DEPLOY_DIR}/

# 3. 上传配置文件
echo "3. 上传配置文件..."
sshpass -p "${SERVER_PASSWORD}" scp -o StrictHostKeyChecking=no aagro-server/src/main/resources/*.yaml ${SERVER_USER}@${SERVER_HOST}:${DEPLOY_DIR}/config/

# 4. 创建启动脚本
echo "4. 创建启动脚本..."
cat > start.sh << 'EOF'
#!/bin/bash

APP_NAME="aagro-server"
JAR_FILE="/data/java/aiotagro/aagro-server.jar"
PID_FILE="/data/java/aiotagro/app.pid"
LOG_FILE="/data/java/aiotagro/logs/app.log"

# 检查Java环境
if ! command -v java &> /dev/null; then
    echo "Java未安装，请先安装Java 8或更高版本"
    exit 1
fi

# 停止现有进程
if [ -f "$PID_FILE" ]; then
    PID=$(cat $PID_FILE)
    if ps -p $PID > /dev/null 2>&1; then
        echo "停止现有进程 $PID..."
        kill $PID
        sleep 5
        if ps -p $PID > /dev/null 2>&1; then
            echo "强制停止进程 $PID..."
            kill -9 $PID
        fi
    fi
    rm -f $PID_FILE
fi

# 启动应用
echo "启动应用..."
nohup java -jar $JAR_FILE \
    --spring.config.location=file:/data/java/aiotagro/config/ \
    --spring.profiles.active=remote \
    --server.port=8080 \
    > $LOG_FILE 2>&1 &

# 保存PID
echo $! > $PID_FILE
echo "应用已启动，PID: $(cat $PID_FILE)"
echo "日志文件: $LOG_FILE"
echo "可以使用以下命令查看日志:"
echo "tail -f $LOG_FILE"
EOF

sshpass -p "${SERVER_PASSWORD}" scp -o StrictHostKeyChecking=no start.sh ${SERVER_USER}@${SERVER_HOST}:${DEPLOY_DIR}/
sshpass -p "${SERVER_PASSWORD}" ssh -o StrictHostKeyChecking=no ${SERVER_USER}@${SERVER_HOST} "chmod +x ${DEPLOY_DIR}/start.sh"

# 5. 创建停止脚本
echo "5. 创建停止脚本..."
cat > stop.sh << 'EOF'
#!/bin/bash

PID_FILE="/data/java/aiotagro/app.pid"

if [ -f "$PID_FILE" ]; then
    PID=$(cat $PID_FILE)
    if ps -p $PID > /dev/null 2>&1; then
        echo "停止进程 $PID..."
        kill $PID
        sleep 5
        if ps -p $PID > /dev/null 2>&1; then
            echo "强制停止进程 $PID..."
            kill -9 $PID
        fi
        echo "应用已停止"
    else
        echo "进程不存在"
    fi
    rm -f $PID_FILE
else
    echo "PID文件不存在"
fi
EOF

sshpass -p "${SERVER_PASSWORD}" scp -o StrictHostKeyChecking=no stop.sh ${SERVER_USER}@${SERVER_HOST}:${DEPLOY_DIR}/
sshpass -p "${SERVER_PASSWORD}" ssh -o StrictHostKeyChecking=no ${SERVER_USER}@${SERVER_HOST} "chmod +x ${DEPLOY_DIR}/stop.sh"

echo "部署完成！"
echo "服务器目录: ${DEPLOY_DIR}"
echo "启动命令: ssh ${SERVER_USER}@${SERVER_HOST} 'cd ${DEPLOY_DIR} && ./start.sh'"
echo "停止命令: ssh ${SERVER_USER}@${SERVER_HOST} 'cd ${DEPLOY_DIR} && ./stop.sh'"
echo "查看日志: ssh ${SERVER_USER}@${SERVER_HOST} 'tail -f ${DEPLOY_DIR}/logs/app.log'"