#!/bin/bash
# DevOps 监听器 PM2 后台启动脚本

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

echo "=========================================="
echo "RuoYi-Cloud DevOps PM2 后台启动"
echo "=========================================="

# 1. 配置 npm 镜像源
echo "[步骤 1/7] 配置 npm 镜像源..."
npm config set registry https://registry.npmmirror.com
echo "✓ npm 镜像源配置完成"

# 2. 检查并安装 PM2
echo ""
echo "[步骤 2/7] 检查 PM2 安装状态..."
if ! command -v pm2 &> /dev/null; then
    echo "PM2 未安装，开始安装..."
    npm install -g pm2
    echo "✓ PM2 安装完成"
else
    echo "✓ PM2 已安装"
fi

# 3. 检查 Python 环境
echo ""
echo "[步骤 3/7] 检查 Python 环境..."
if ! command -v python3 &> /dev/null; then
    echo "错误: 未找到 python3"
    exit 1
fi
echo "✓ Python3 已安装: $(python3 --version)"

# 4. 检查 Python 依赖
echo ""
echo "[步骤 4/7] 检查 Python 依赖..."
if ! python3 -c "import yaml" 2>/dev/null; then
    echo "安装 PyYAML..."
    pip3 install --user PyYAML
fi
echo "✓ Python 依赖检查完成"

# 5. 删除已存在的 PM2 进程
echo ""
echo "[步骤 5/7] 清理已存在的 PM2 进程..."
if pm2 describe devops-monitor &> /dev/null; then
    echo "发现已存在的 devops-monitor 进程，正在删除..."
    pm2 delete devops-monitor
    echo "✓ 已删除旧进程"
else
    echo "✓ 无需清理"
fi

# 6. 启动 PM2 进程
echo ""
echo "[步骤 6/7] 启动 DevOps 监听器..."
cd "$PROJECT_ROOT"
pm2 start "$SCRIPT_DIR/monitor.py" \
    --name devops-monitor \
    --interpreter python3 \
    --cwd "$PROJECT_ROOT" \
    --log "$SCRIPT_DIR/logs/pm2.log" \
    --error "$SCRIPT_DIR/logs/pm2-error.log" \
    --output "$SCRIPT_DIR/logs/pm2-output.log"

echo "✓ DevOps 监听器启动成功"

# 7. 显示进程状态
echo ""
echo "[步骤 7/7] 查看进程状态..."
pm2 list

# 8. 设置开机自启动
echo ""
echo "=========================================="
echo "配置开机自启动"
echo "=========================================="
echo "正在配置 PM2 开机自启动..."
echo "注意: 此步骤可能需要输入密码"
pm2 startup

echo ""
echo "保存 PM2 进程列表..."
pm2 save

echo ""
echo "=========================================="
echo "启动完成"
echo "=========================================="
echo ""
echo "常用命令:"
echo "  pm2 list              - 查看所有进程"
echo "  pm2 logs devops-monitor  - 查看日志"
echo "  pm2 stop devops-monitor  - 停止进程"
echo "  pm2 restart devops-monitor - 重启进程"
echo "  pm2 delete devops-monitor  - 删除进程"
echo ""