#!/bin/bash

# =============================================
# LJ360 全景监控服务管理脚本 - 增强版
# 基于步骤化提示、彩色输出、友好交互
# 适用于 RK3588 / Linux 本地或远程管理
# =============================================

# ---------------------------------------------
# 初始化设置
# ---------------------------------------------

# 遇到错误立即退出
set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
PURPLE='\033[0;35m'
NC='\033[0m' # No Color

# 进度与状态打印函数
print_header() {
    clear
    echo -e "${PURPLE}"
    echo "╔══════════════════════════════════════════════════════╗"
    echo "║           LJ360 全景监控服务管理工具 (增强版)         ║"
    echo "║                  RK3588 / Linux                      ║"
    echo "╚══════════════════════════════════════════════════════╝"
    echo -e "${NC}"
}

print_step() {
    echo -e "${BLUE}[STEP $1/$2]${NC} $3"
}

print_success() {
    echo -e "${GREEN}✓${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}⚠${NC} $1"
}

print_error() {
    echo -e "${RED}✗${NC} $1"
}

print_progress() {
    echo -e "${CYAN}[进度]${NC} $1"
}

print_divider() {
    echo -e "${BLUE}──────────────────────────────────────────────${NC}"
}

# ---------------------------------------------
# 全局配置
# ---------------------------------------------

TOTAL_STEPS=9
STEP=1

SERVICE_NAME="lj360.service"
WATCHDOG_SERVICE="lj360_watchdog.service"

# 获取当前用户
CURRENT_USER=$(whoami)

# 检查是否以 root 运行
if [ "$EUID" -eq 0 ]; then
    print_error "❌ 请勿使用 root 用户运行此脚本。"
    print_error "✅ 请使用以下命令运行（普通用户）："
    print_error "    bash $0"
    exit 1
fi

# 项目目录
PROJECT_DIR="/home/$CURRENT_USER/LJ360"

print_header
print_success "🔧 当前用户: $CURRENT_USER"
print_success "📂 项目目录: $PROJECT_DIR"
echo ""

# ---------------------------------------------
# 主菜单逻辑与步骤化功能
# ---------------------------------------------

main_menu() {
    while true; do
        show_status
        
        echo -e "${CYAN}🔧 请选择要执行的操作:${NC}"
        print_divider
        echo "1) 🛠️   安装 LJ360 全景监控服务"
        echo "2) 🛡️   安装并启动看门狗服务"
        echo "3) ▶️    启动全景监控服务"
        echo "4) ⏹️    停止全景监控服务"
        echo "5) 🔄   重启全景监控服务"
        echo "6) 🔔   启用开机自启"
        echo "7) 🚫   禁用开机自启"
        echo "8) 📜   查看实时日志"
        echo "9) 📊   查看系统状态"
        echo "10) 🧹  卸载 LJ360 服务"
        echo "0) 🚪   退出脚本"
        print_divider
        
        read -p "👉 请输入选项 [0-10]: " choice
        
        case $choice in
            1)
                STEP=1
                install_service
                ;;
            2)
                STEP=1
                install_watchdog_service
                ;;
            3)
                STEP=1
                start_service
                ;;
            4)
                STEP=1
                stop_service
                ;;
            5)
                STEP=1
                restart_service
                ;;
            6)
                STEP=1
                enable_service
                ;;
            7)
                STEP=1
                disable_service
                ;;
            8)
                STEP=1
                view_logs
                ;;
            9)
                STEP=1
                view_status
                ;;
            10)
                STEP=1
                uninstall_service
                ;;
            0)
                print_success "👋 再见！脚本已退出。"
                exit 0
                ;;
            *)
                print_error "❌ 无效选项，请重新输入 [0-10]"
                sleep 2
                ;;
        esac
    done
}

# ---------------------------------------------
# 功能函数
# ---------------------------------------------

show_status() {
    print_header
    
    echo -e "${BLUE}【📊 当前服务状态】${NC}"
    print_divider
    
    # 检查主服务状态
    if systemctl is-active --quiet $SERVICE_NAME 2>/dev/null; then
        echo -e "${GREEN}● LJ360 服务正在运行 ✅${NC}"
    else
        echo -e "${RED}● LJ360 服务未运行 ❌${NC}"
    fi
    
    # 检查看门狗服务状态
    if systemctl is-active --quiet $WATCHDOG_SERVICE 2>/dev/null; then
        echo -e "${GREEN}● 看门狗服务正在运行 🛡️${NC}"
    else
        echo -e "${YELLOW}● 看门狗服务未运行 ⚠${NC}"
    fi
    
    # 检查开机自启状态
    if systemctl is-enabled $SERVICE_NAME 2>/dev/null; then
        echo -e "${GREEN}● 开机自启已启用 ✅${NC}"
    else
        echo -e "${YELLOW}● 开机自启未启用 ⚠${NC}"
    fi
    
    # 检查Web端口
    echo ""
    echo -e "${BLUE}【🌐 网络端口状态】${NC}"
    print_divider
    if netstat -tlnp 2>/dev/null | grep -q ":5000"; then
        echo -e "${GREEN}● Web 服务端口 5000 已监听 ✅${NC}"
    else
        echo -e "${RED}● Web 服务端口 5000 未监听 ❌${NC}"
    fi
    
    echo ""
}

# --------------------------
# Step 1: 安装服务
# --------------------------
install_service() {
    print_step $STEP $TOTAL_STEPS "安装 LJ360 全景监控服务"
    
    # 检查项目目录是否存在
    if [ ! -d "$PROJECT_DIR" ]; then
        print_error "❌ 项目目录不存在: $PROJECT_DIR"
        print_error "请确认项目路径是否正确"
        read -p "🔘 按 Enter 继续..." -r
        return
    fi
    
    # 检查web.py文件是否存在
    if [ ! -f "$PROJECT_DIR/web.py" ]; then
        print_error "❌ web.py 文件不存在: $PROJECT_DIR/web.py"
        print_error "请确认项目文件是否正确"
        read -p "🔘 按 Enter 继续..." -r
        return
    fi
    
    # 创建启动脚本
    local START_SCRIPT="$PROJECT_DIR/start_lj360.sh"
    print_progress "🔧 创建启动脚本: $START_SCRIPT"
    cat > "$START_SCRIPT" << EOF
#!/bin/bash
# LJ360 全景监控启动脚本
# 项目目录: $PROJECT_DIR

# 切换到项目目录
cd "$PROJECT_DIR"

# 设置环境变量
export DISPLAY=:0
export XAUTHORITY=/home/$CURRENT_USER/.Xauthority
export PYTHONPATH=$PROJECT_DIR:\$PYTHONPATH

# 日志文件
LOG_FILE="$PROJECT_DIR/lj360.log"
ERROR_LOG="$PROJECT_DIR/lj360_error.log"

echo "=========================================" >> "\$LOG_FILE"
echo "LJ360 启动时间: \$(date)" >> "\$LOG_FILE"
echo "=========================================" >> "\$LOG_FILE"

# 检查是否已有进程在运行
if pgrep -f "python3 web.py" > /dev/null; then
    echo "\$(date): LJ360 应用已在运行，跳过启动" >> "\$LOG_FILE"
    exit 0
fi

# 启动应用并记录输出
echo "\$(date): 启动 LJ360 web.py..." >> "\$LOG_FILE"
exec python3 web.py >> "\$LOG_FILE" 2>> "\$ERROR_LOG"
EOF
    
    chmod +x "$START_SCRIPT"
    chown "$CURRENT_USER:$CURRENT_USER" "$START_SCRIPT"
    print_success "✅ 启动脚本已创建并授权"
    
    # 创建 systemd 服务
    print_progress "🔧 创建 systemd 服务文件: /etc/systemd/system/$SERVICE_NAME"
    sudo tee /etc/systemd/system/$SERVICE_NAME > /dev/null << EOF
[Unit]
Description=LJ360 Surround View Service
After=network.target graphical.target
Wants=network.target graphical.target

[Service]
Type=simple
User=$CURRENT_USER
WorkingDirectory=$PROJECT_DIR
Environment="DISPLAY=:0"
Environment="XAUTHORITY=/home/$CURRENT_USER/.Xauthority"
Environment="PYTHONPATH=$PROJECT_DIR"
Environment="XDG_RUNTIME_DIR=/run/user/1000"
ExecStart=$PROJECT_DIR/start_lj360.sh
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal

# 限制资源使用（可选）
# MemoryMax=1G
# CPUQuota=80%

[Install]
WantedBy=multi-user.target
EOF
    
    sudo systemctl daemon-reload
    print_success "✅ systemd 服务文件已部署 & 缓存已刷新"
    
    STEP=$((STEP + 1))
    read -p "🔘 按 Enter 继续..." -r
}

# --------------------------
# Step 2: 安装看门狗服务
# --------------------------
install_watchdog_service() {
    print_step $STEP $TOTAL_STEPS "安装并启动看门狗服务"
    
    # 创建看门狗脚本
    local WATCHDOG_SCRIPT="$PROJECT_DIR/watchdog_lj360.sh"
    print_progress "🔧 创建看门狗脚本: $WATCHDOG_SCRIPT"
    cat > "$WATCHDOG_SCRIPT" << EOF
#!/bin/bash
# LJ360 看门狗服务脚本
# 项目目录: $PROJECT_DIR

APP_NAME="web.py"
CHECK_INTERVAL=10
LOG_FILE="$PROJECT_DIR/watchdog.log"

echo "=========================================" >> "\$LOG_FILE"
echo "看门狗服务启动时间: \$(date)" >> "\$LOG_FILE"
echo "=========================================" >> "\$LOG_FILE"

while true; do
    # 检查主服务进程是否存在
    if ! pgrep -f "python3 \$APP_NAME" > /dev/null; then
        echo "\$(date): 检测到 LJ360 未运行，正在启动..." >> "\$LOG_FILE"
        
        cd "$PROJECT_DIR"
        
        # 设置环境变量
        export DISPLAY=:0
        export XAUTHORITY=/home/$CURRENT_USER/.Xauthority
        export PYTHONPATH=$PROJECT_DIR:\$PYTHONPATH
        
        # 启动应用
        nohup python3 web.py >> "$PROJECT_DIR/lj360.log" 2>> "$PROJECT_DIR/lj360_error.log" &
        
        echo "\$(date): 已启动 LJ360，PID: \$!" >> "\$LOG_FILE"
        
        # 等待应用启动
        sleep 5
    fi
    
    sleep \$CHECK_INTERVAL
done
EOF
    
    chmod +x "$WATCHDOG_SCRIPT"
    chown "$CURRENT_USER:$CURRENT_USER" "$WATCHDOG_SCRIPT"
    print_success "✅ 看门狗脚本已创建并授权"
    
    # 创建看门狗 systemd 服务
    print_progress "🔧 创建看门狗服务文件: /etc/systemd/system/$WATCHDOG_SERVICE"
    sudo tee /etc/systemd/system/$WATCHDOG_SERVICE > /dev/null << EOF
[Unit]
Description=LJ360 Watchdog Service
After=network.target
Wants=network.target

[Service]
Type=simple
User=$CURRENT_USER
WorkingDirectory=$PROJECT_DIR
ExecStart=$PROJECT_DIR/watchdog_lj360.sh
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF
    
    sudo systemctl daemon-reload
    print_success "✅ 看门狗服务文件已部署"
    
    # 启用并启动看门狗服务
    print_progress "🚀 启动看门狗服务"
    sudo systemctl enable $WATCHDOG_SERVICE
    sudo systemctl start $WATCHDOG_SERVICE
    sleep 2
    
    if systemctl is-active --quiet $WATCHDOG_SERVICE; then
        print_success "✅ 看门狗服务启动成功"
    else
        print_warning "⚠️ 看门狗服务启动可能有问题，请查看日志"
    fi
    
    STEP=$((STEP + 1))
    read -p "🔘 按 Enter 继续..." -r
}

# --------------------------
# Step 3: 启动服务
# --------------------------
start_service() {
    print_step $STEP $TOTAL_STEPS "启动 LJ360 全景监控服务"
    
    # 检查服务文件是否存在
    if [ ! -f "/etc/systemd/system/$SERVICE_NAME" ]; then
        print_error "❌ 服务未安装，请先安装服务"
        read -p "🔘 按 Enter 继续..." -r
        return
    fi
    
    print_progress "🚀 正在启动服务: $SERVICE_NAME"
    sudo systemctl start "$SERVICE_NAME"
    sleep 3
    
    # 检查启动状态
    if systemctl is-active --quiet "$SERVICE_NAME"; then
        print_success "✅ 服务启动成功"
        
        # 检查Web端口
        sleep 2
        if netstat -tlnp 2>/dev/null | grep -q ":5000"; then
            local IP_ADDR=$(hostname -I | awk '{print $1}')
            print_success "🌐 Web 服务已启动: http://$IP_ADDR:5000"
            print_success "🌐 本地访问: http://localhost:5000"
        fi
    else
        print_warning "⚠️ 服务启动可能有问题，请查看日志"
    fi
    
    STEP=$((STEP + 1))
    read -p "🔘 按 Enter 继续..." -r
}

# --------------------------
# Step 4: 停止服务
# --------------------------
stop_service() {
    print_step $STEP $TOTAL_STEPS "停止 LJ360 全景监控服务"
    
    # 检查服务文件是否存在
    if [ ! -f "/etc/systemd/system/$SERVICE_NAME" ]; then
        print_error "❌ 服务未安装，请先安装服务"
        read -p "🔘 按 Enter 继续..." -r
        return
    fi
    
    print_progress "⏹️  正在停止服务: $SERVICE_NAME"
    sudo systemctl stop "$SERVICE_NAME"
    sleep 2
    
    # 清理可能的残留进程
    print_progress "🧹 清理残留进程..."
    pkill -f "python3 web.py" 2>/dev/null || true
    
    # 检查停止状态
    if ! systemctl is-active --quiet "$SERVICE_NAME"; then
        print_success "✅ 服务停止成功"
    else
        print_warning "⚠️ 服务停止可能有问题"
    fi
    
    STEP=$((STEP + 1))
    read -p "🔘 按 Enter 继续..." -r
}

# --------------------------
# Step 5: 重启服务
# --------------------------
restart_service() {
    print_step $STEP $TOTAL_STEPS "重启 LJ360 全景监控服务"
    
    # 检查服务文件是否存在
    if [ ! -f "/etc/systemd/system/$SERVICE_NAME" ]; then
        print_error "❌ 服务未安装，请先安装服务"
        read -p "🔘 按 Enter 继续..." -r
        return
    fi
    
    print_progress "🔄 正在重启服务: $SERVICE_NAME"
    sudo systemctl restart "$SERVICE_NAME"
    sleep 3
    
    # 检查重启状态
    if systemctl is-active --quiet "$SERVICE_NAME"; then
        print_success "✅ 服务重启成功"
        
        # 检查Web端口
        sleep 2
        if netstat -tlnp 2>/dev/null | grep -q ":5000"; then
            local IP_ADDR=$(hostname -I | awk '{print $1}')
            print_success "🌐 Web 服务已重启: http://$IP_ADDR:5000"
        fi
    else
        print_warning "⚠️ 服务重启可能有问题，请查看日志"
    fi
    
    STEP=$((STEP + 1))
    read -p "🔘 按 Enter 继续..." -r
}

# --------------------------
# Step 6: 启用开机自启
# --------------------------
enable_service() {
    print_step $STEP $TOTAL_STEPS "启用开机自启"
    
    # 检查服务文件是否存在
    if [ ! -f "/etc/systemd/system/$SERVICE_NAME" ]; then
        print_error "❌ 服务未安装，请先安装服务"
        read -p "🔘 按 Enter 继续..." -r
        return
    fi
    
    print_progress "🔔 正在启用开机自启: $SERVICE_NAME"
    sudo systemctl enable "$SERVICE_NAME"
    sleep 1
    
    if systemctl is-enabled "$SERVICE_NAME"; then
        print_success "✅ 开机自启已启用"
    else
        print_error "❌ 开机自启启用失败"
    fi
    
    STEP=$((STEP + 1))
    read -p "🔘 按 Enter 继续..." -r
}

# --------------------------
# Step 7: 禁用开机自启
# --------------------------
disable_service() {
    print_step $STEP $TOTAL_STEPS "禁用开机自启"
    
    # 检查服务文件是否存在
    if [ ! -f "/etc/systemd/system/$SERVICE_NAME" ]; then
        print_error "❌ 服务未安装，请先安装服务"
        read -p "🔘 按 Enter 继续..." -r
        return
    fi
    
    print_progress "🚫 正在禁用开机自启: $SERVICE_NAME"
    sudo systemctl disable "$SERVICE_NAME"
    sleep 1
    
    if ! systemctl is-enabled "$SERVICE_NAME"; then
        print_success "✅ 开机自启已禁用"
    else
        print_error "❌ 开机自启禁用失败"
    fi
    
    STEP=$((STEP + 1))
    read -p "🔘 按 Enter 继续..." -r
}

# --------------------------
# Step 8: 查看日志
# --------------------------
view_logs() {
    print_step $STEP $TOTAL_STEPS "查看实时日志"
    
    # 检查服务文件是否存在
    if [ ! -f "/etc/systemd/system/$SERVICE_NAME" ]; then
        print_error "❌ 服务未安装，请先安装服务"
        read -p "🔘 按 Enter 继续..." -r
        return
    fi
    
    print_progress "📜 请选择要查看的日志类型:"
    echo "1) 📋 查看 systemd 服务日志"
    echo "2) 📄 查看应用日志文件"
    echo "3) ⚠️  查看错误日志文件"
    echo "4) 🛡️  查看看门狗日志"
    print_divider
    
    read -p "👉 请选择 [1-4]: " log_choice
    
    case $log_choice in
        1)
            print_progress "📜 正在打开 systemd 服务日志（按 Ctrl+C 退出）"
            echo ""
            sudo journalctl -u "$SERVICE_NAME" -f
            ;;
        2)
            print_progress "📄 正在查看应用日志文件: $PROJECT_DIR/lj360.log"
            echo ""
            if [ -f "$PROJECT_DIR/lj360.log" ]; then
                tail -50 "$PROJECT_DIR/lj360.log"
                echo ""
                echo "按 Enter 查看更多，或按 Ctrl+C 退出..."
                tail -f "$PROJECT_DIR/lj360.log"
            else
                print_error "❌ 日志文件不存在"
            fi
            ;;
        3)
            print_progress "⚠️  正在查看错误日志文件: $PROJECT_DIR/lj360_error.log"
            echo ""
            if [ -f "$PROJECT_DIR/lj360_error.log" ]; then
                tail -50 "$PROJECT_DIR/lj360_error.log"
            else
                print_warning "⚠️  错误日志文件不存在"
            fi
            ;;
        4)
            print_progress "🛡️  正在查看看门狗日志文件: $PROJECT_DIR/watchdog.log"
            echo ""
            if [ -f "$PROJECT_DIR/watchdog.log" ]; then
                tail -50 "$PROJECT_DIR/watchdog.log"
            else
                print_warning "⚠️  看门狗日志文件不存在"
            fi
            ;;
        *)
            print_error "❌ 无效选项"
            ;;
    esac
    
    STEP=$((STEP + 1))
    read -p "🔘 日志查看结束，按 Enter 继续..." -r
}

# --------------------------
# Step 9: 查看系统状态
# --------------------------
view_status() {
    print_step $STEP $TOTAL_STEPS "查看详细系统状态"
    
    echo -e "${CYAN}【📊 系统资源状态】${NC}"
    print_divider
    
    # CPU使用率
    echo -e "${BLUE}● CPU 使用率:${NC}"
    top -bn1 | grep "Cpu(s)" | awk '{print "  " $2 "% user, " $4 "% system, " $8 "% idle"}'
    
    # 内存使用
    echo -e "${BLUE}● 内存使用:${NC}"
    free -h | awk '/^Mem:/ {print "  " $3 " / " $2 " (" $3/$2*100 "%) used"}'
    
    # 磁盘空间
    echo -e "${BLUE}● 磁盘空间:${NC}"
    df -h /home | awk 'NR==2 {print "  " $3 " / " $2 " (" $5 ") used"}'
    
    echo ""
    echo -e "${CYAN}【🔍 进程状态】${NC}"
    print_divider
    
    # LJ360相关进程
    if pgrep -f "python3 web.py" > /dev/null; then
        echo -e "${GREEN}● LJ360 进程正在运行 ✅${NC}"
        ps aux | grep "python3 web.py" | grep -v grep | awk '{print "  PID: " $2 ", CPU: " $3 "%, MEM: " $4 "%, CMD: " $11}'
    else
        echo -e "${RED}● LJ360 进程未运行 ❌${NC}"
    fi
    
    echo ""
    echo -e "${CYAN}【📈 服务运行时间】${NC}"
    print_divider
    
    if systemctl is-active --quiet $SERVICE_NAME; then
        UPTIME=$(systemctl show $SERVICE_NAME --property=ActiveEnterTimestamp | awk -F= '{print $2}')
        echo -e "${GREEN}● 服务启动时间: $UPTIME${NC}"
    fi
    
    if systemctl is-active --quiet $WATCHDOG_SERVICE; then
        WATCHDOG_UPTIME=$(systemctl show $WATCHDOG_SERVICE --property=ActiveEnterTimestamp | awk -F= '{print $2}')
        echo -e "${GREEN}● 看门狗启动时间: $WATCHDOG_UPTIME${NC}"
    fi
    
    STEP=$((STEP + 1))
    read -p "🔘 按 Enter 继续..." -r
}

# --------------------------
# Step 10: 卸载服务
# --------------------------
uninstall_service() {
    print_step $STEP $TOTAL_STEPS "卸载 LJ360 全景监控服务"
    echo -e "${RED}⚠ 警告：此操作将卸载 LJ360 全景监控服务！${NC}"
    echo -n "✅ 确定要卸载吗？(y/N): "
    read -r confirm
    if [[ $confirm =~ ^[Yy]$ ]]; then
        print_progress "⏹️  停止服务..."
        sudo systemctl stop "$SERVICE_NAME" 2>/dev/null || true
        sudo systemctl stop "$WATCHDOG_SERVICE" 2>/dev/null || true
        
        print_progress "🚫 禁用开机自启..."
        sudo systemctl disable "$SERVICE_NAME" 2>/dev/null || true
        sudo systemctl disable "$WATCHDOG_SERVICE" 2>/dev/null || true
        
        print_progress "🗑️  删除 systemd 服务文件..."
        sudo rm -f /etc/systemd/system/"$SERVICE_NAME"
        sudo rm -f /etc/systemd/system/"$WATCHDOG_SERVICE"
        sudo systemctl daemon-reload
        sudo systemctl reset-failed
        
        print_progress "🗑️  删除启动脚本..."
        rm -f "$PROJECT_DIR/start_lj360.sh"
        rm -f "$PROJECT_DIR/watchdog_lj360.sh"
        
        print_progress "🔪 清理进程..."
        pkill -f "python3 web.py" 2>/dev/null || true
        pkill -f "watchdog_lj360.sh" 2>/dev/null || true
        
        print_success "✅ LJ360 全景监控服务卸载完成"
        print_warning "📝 日志文件保留在: $PROJECT_DIR/"
        print_warning "   - lj360.log"
        print_warning "   - lj360_error.log"
        print_warning "   - watchdog.log"
    else
        print_warning "❌ 取消卸载操作"
    fi
    
    STEP=$((STEP + 1))
    read -p "🔘 按 Enter 继续..." -r
}

# ---------------------------------------------
# 启动主菜单
# ---------------------------------------------

# 检查是否在正确的目录运行
if [ ! -d "$PROJECT_DIR" ]; then
    print_error "❌ 项目目录不存在: $PROJECT_DIR"
    print_error "请确认项目路径是否正确，或者修改脚本中的 PROJECT_DIR 变量"
    exit 1
fi

main_menu