#!/bin/bash
# SafeSight Control 统一管理脚本
# 提供安装、状态、升级、卸载等功能

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 配置
APP_NAME="safesightd"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
DEFAULT_INSTALL_DIR="/opt/safesightd"
INSTALL_DIR="${DEFAULT_INSTALL_DIR}"
PID_FILE="$INSTALL_DIR/$APP_NAME.pid"

# 显示帮助
cmd_help() {
    cat << EOF
SafeSight Control 管理脚本

用法: $0 <命令> [选项]

命令:
    install [目录]    安装服务 (默认: /opt/safesightd)
    status            查看服务状态
    start             启动服务
    stop              停止服务
    restart           重启服务
    upgrade [目录]    升级服务 (保留配置)
    uninstall [目录]  卸载服务 (自动备份配置)
    check             检查环境是否满足运行要求
    help              显示此帮助信息

示例:
    $0 install                    # 安装到默认目录
    $0 install /usr/local/3588    # 安装到指定目录
    $0 status                     # 查看服务状态
    $0 upgrade                    # 升级到当前目录下的新版本
    $0 uninstall                  # 卸载并备份配置
    $0 check                      # 检查系统环境

快捷命令 (安装后可用):
    3588admin-start    启动服务
    3588admin-stop     停止服务
    3588admin-status   查看状态
EOF
}

# 检查 root 权限
check_root() {
    if [ "$EUID" -ne 0 ]; then
        echo -e "${RED}错误: 请使用 sudo 运行此命令${NC}"
        exit 1
    fi
}

# 获取安装目录
get_install_dir() {
    if [ -n "$1" ]; then
        INSTALL_DIR="$1"
    fi
    PID_FILE="$INSTALL_DIR/$APP_NAME.pid"
}

# 环境检查
cmd_check() {
    echo "========== SafeSight Control 环境检查 =========="
    echo ""
    
    PASS=0
    FAIL=0
    WARN=0

    check_pass() {
        echo -e "${GREEN}✓${NC} $1"
        ((PASS++))
    }

    check_fail() {
        echo -e "${RED}✗${NC} $1"
        ((FAIL++))
    }

    check_warn() {
        echo -e "${YELLOW}⚠${NC} $1"
        ((WARN++))
    }

    # 1. 检查操作系统
    echo "[系统信息]"
    echo "  主机名: $(hostname)"
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        echo "  操作系统: $NAME $VERSION"
        if [[ "$NAME" == *"Ubuntu"* ]] && [[ "$VERSION_ID" == "22.04" ]]; then
            check_pass "Ubuntu 22.04 detected"
        else
            check_warn "非 Ubuntu 22.04，可能兼容但未经测试"
        fi
    else
        check_warn "无法检测操作系统版本"
    fi

    # 2. 检查架构
    echo ""
    echo "[硬件信息]"
    ARCH=$(uname -m)
    echo "  架构: $ARCH"
    if [ "$ARCH" = "x86_64" ]; then
        check_pass "x86_64 架构"
    elif [ "$ARCH" = "aarch64" ]; then
        check_warn "ARM64 架构，请使用 ARM64 版本二进制"
    else
        check_warn "未知架构: $ARCH"
    fi

    echo "  CPU: $(nproc) 核"
    echo "  内存: $(free -h | awk '/^Mem:/ {print $2}')"

    # 3. 检查网络工具
    echo ""
    echo "[网络工具]"
    if command -v curl >/dev/null 2>&1; then
        check_pass "curl 已安装"
    else
        check_warn "curl 未安装"
    fi

    if command -v netstat >/dev/null 2>&1 || command -v ss >/dev/null 2>&1; then
        check_pass "网络工具(netstat/ss)已安装"
    else
        check_warn "建议安装 net-tools 或 iproute2"
    fi

    # 4. 检查端口占用
    echo ""
    echo "[端口检查]"
    PORT_18080=false
    PORT_35688=false

    if command -v ss >/dev/null 2>&1; then
        PORT_18080=$(ss -tln 2>/dev/null | grep -q ':18080 ' && echo true || echo false)
        PORT_35688=$(ss -uln 2>/dev/null | grep -q ':35688 ' && echo true || echo false)
    elif command -v netstat >/dev/null 2>&1; then
        PORT_18080=$(netstat -tln 2>/dev/null | grep -q ':18080 ' && echo true || echo false)
        PORT_35688=$(netstat -uln 2>/dev/null | grep -q ':35688 ' && echo true || echo false)
    fi

    if [ "$PORT_18080" = true ]; then
        check_warn "端口 18080 已被占用"
    else
        check_pass "端口 18080 可用"
    fi

    if [ "$PORT_35688" = true ]; then
        check_warn "端口 35688 已被占用"
    else
        check_pass "端口 35688 可用"
    fi

    # 5. 检查防火墙
    echo ""
    echo "[防火墙]"
    if command -v ufw >/dev/null 2>&1; then
        UFW_STATUS=$(ufw status 2>/dev/null | grep -i status | awk '{print $2}')
        echo "  UFW 状态: $UFW_STATUS"
    elif command -v firewall-cmd >/dev/null 2>&1; then
        check_warn "检测到 firewalld，请手动配置端口"
    else
        echo "  未检测到防火墙"
    fi

    # 6. 检查磁盘空间
    echo ""
    echo "[磁盘空间]"
    DISK_AVAIL=$(df -BG /opt 2>/dev/null | tail -1 | awk '{print $4}' | tr -d 'G')
    if [ -z "$DISK_AVAIL" ]; then
        DISK_AVAIL=$(df -BG / 2>/dev/null | tail -1 | awk '{print $4}' | tr -d 'G')
    fi

    if [ -n "$DISK_AVAIL" ] && [ "$DISK_AVAIL" -ge 1 ]; then
        check_pass "磁盘空间充足 (${DISK_AVAIL}G 可用)"
    else
        check_warn "磁盘空间不足 (${DISK_AVAIL:-0}G 可用，建议至少 1GB)"
    fi

    # 7. 检查权限
    echo ""
    echo "[权限检查]"
    if [ "$EUID" -eq 0 ]; then
        check_pass "当前为 root 用户"
    else
        check_warn "当前非 root 用户，安装需要 root 权限"
    fi

    # 8. 检查 Python
    echo ""
    echo "[其他工具]"
    if command -v python3 >/dev/null 2>&1; then
        check_pass "Python3 已安装 ($(python3 --version))"
    else
        check_warn "Python3 未安装 (用于配置验证)"
    fi

    # 总结
    echo ""
    echo "========== 检查总结 =========="
    echo -e "通过: ${GREEN}$PASS${NC}  警告: ${YELLOW}$WARN${NC}  失败: ${RED}$FAIL${NC}"
    echo ""

    if [ $FAIL -gt 0 ]; then
        echo -e "${RED}环境检查未通过，请解决上述问题后再安装${NC}"
        exit 1
    elif [ $WARN -gt 0 ]; then
        echo -e "${YELLOW}环境基本满足，但有一些警告需要注意${NC}"
        return 0
    else
        echo -e "${GREEN}环境检查全部通过，可以安装${NC}"
        return 0
    fi
}

# 安装
cmd_install() {
    check_root
    get_install_dir "$1"
    
    local CURRENT_DIR="$SCRIPT_DIR"
    local BASE_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
    
    echo "========== SafeSight Control 离线安装 =========="
    echo "安装目录: $INSTALL_DIR"
    echo ""

    # 检查安装目录
    if [ -d "$INSTALL_DIR" ] && [ "$(ls -A $INSTALL_DIR 2>/dev/null)" ]; then
        echo -e "${YELLOW}警告: 安装目录 $INSTALL_DIR 已存在且不为空${NC}"
        read -p "是否覆盖? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            echo "安装已取消"
            exit 1
        fi
        # 备份现有配置
        if [ -f "$INSTALL_DIR/config/safesightd.json" ]; then
            local BACKUP_FILE="$INSTALL_DIR/config/safesightd.json.bak.$(date +%Y%m%d%H%M%S)"
            echo "备份现有配置到: $BACKUP_FILE"
            cp "$INSTALL_DIR/config/safesightd.json" "$BACKUP_FILE"
        fi
    fi

    # 1. 安装依赖包
    if [ -d "$BASE_DIR/deps" ] && [ "$(ls -A $BASE_DIR/deps/*.deb 2>/dev/null)" ]; then
        echo "[1/5] 安装依赖包..."
        cd "$BASE_DIR/deps"
        for pkg in *.deb; do
            echo "  安装: $pkg"
            dpkg -i "$pkg" 2>/dev/null || true
        done
        apt-get install -f -y 2>/dev/null || true
    else
        echo "[1/5] 跳过依赖包安装 (无依赖包)"
    fi

    # 2. 创建安装目录
    echo "[2/5] 创建安装目录..."
    mkdir -p "$INSTALL_DIR"
    
    echo "  复制二进制文件..."
    mkdir -p "$INSTALL_DIR/bin"
    cp "$BASE_DIR/bin/safesightd" "$INSTALL_DIR/bin/" 2>/dev/null || {
        echo -e "${RED}错误: 未找到 safesightd 二进制文件${NC}"
        echo "请确保在打包前已编译"
        exit 1
    }

    echo "  复制配置文件..."
    mkdir -p "$INSTALL_DIR/config"
    if [ -f "$BASE_DIR/config/safesightd.json" ]; then
        cp "$BASE_DIR/config/safesightd.json" "$INSTALL_DIR/config/"
    elif [ -f "$BASE_DIR/config/safesightd.json.example" ]; then
        cp "$BASE_DIR/config/safesightd.json.example" "$INSTALL_DIR/config/"
    fi

    # 复制模板文件
    if [ -d "$BASE_DIR/templates" ]; then
        echo "  复制模板文件..."
        cp -r "$BASE_DIR/templates" "$INSTALL_DIR/"
    fi

    # 3. 设置权限
    echo "[3/5] 设置权限..."
    chmod +x "$INSTALL_DIR/bin/safesightd"
    mkdir -p "$INSTALL_DIR/logs" || {
        echo -e "${RED}错误: 无法创建日志目录 $INSTALL_DIR/logs${NC}"
        exit 1
    }
    chmod 755 "$INSTALL_DIR/logs" || {
        echo -e "${RED}错误: 无法设置日志目录权限${NC}"
        exit 1
    }

    # 4. 初始化配置文件
    echo "[4/5] 初始化配置文件..."
    if [ ! -f "$INSTALL_DIR/config/safesightd.json" ]; then
        cat > "$INSTALL_DIR/config/safesightd.json" << 'EOF'
{
  "listen": "0.0.0.0:18080",
  "discovery_port": 35688,
  "discovery_timeout_ms": 1200,
  "offline_after_ms": 10000,
  "agent_token": "CHANGE_ME",
  "concurrency": 5
}
EOF
        echo -e "  ${GREEN}已创建默认配置文件${NC}"
        echo -e "  ${YELLOW}⚠️  请编辑 $INSTALL_DIR/config/safesightd.json 修改配置（特别是 agent_token）${NC}"
    else
        echo "  配置文件已存在，保留现有配置"
    fi

    # 5. 复制管理脚本
    echo "[5/5] 安装管理脚本..."
    mkdir -p "$INSTALL_DIR/scripts"
    cp "$CURRENT_DIR/3588admin" "$INSTALL_DIR/scripts/"
    chmod +x "$INSTALL_DIR/scripts/3588admin"

    # 创建快捷方式
    ln -sf "$INSTALL_DIR/scripts/3588admin" /usr/local/bin/3588admin-start 2>/dev/null || true
    ln -sf "$INSTALL_DIR/scripts/3588admin" /usr/local/bin/3588admin-stop 2>/dev/null || true
    ln -sf "$INSTALL_DIR/scripts/3588admin" /usr/local/bin/3588admin-status 2>/dev/null || true
    ln -sf "$INSTALL_DIR/scripts/3588admin" /usr/local/bin/3588admin 2>/dev/null || true

    # 安装 Systemd 服务
    if [ -f "$CURRENT_DIR/3588admin.service" ]; then
        echo "[可选] 安装 Systemd 服务..."
        cp "$CURRENT_DIR/3588admin.service" /etc/systemd/system/
        sed -i "s|/opt/safesightd|$INSTALL_DIR|g" /etc/systemd/system/3588admin.service
        systemctl daemon-reload
        echo "  已安装 Systemd 服务"
    fi

    echo ""
    echo -e "${GREEN}========== 安装完成 ==========${NC}"
    echo "安装目录: $INSTALL_DIR"
    echo ""
    echo "使用命令:"
    echo "  3588admin start     - 启动服务"
    echo "  3588admin stop      - 停止服务"
    echo "  3588admin status    - 查看状态"
    echo "  3588admin restart   - 重启服务"
    echo "  3588admin upgrade   - 升级服务"
    echo "  3588admin uninstall - 卸载服务"
    echo ""
    echo -e "${YELLOW}重要提示:${NC}"
    echo "  1. 请先编辑配置文件: $INSTALL_DIR/config/safesightd.json"
    echo "  2. 务必修改 agent_token 为安全的随机字符串"
    echo ""
    echo -e "${YELLOW}防火墙配置:${NC}"
    echo "  默认监听 0.0.0.0:18080，如需外部访问，请开放防火墙端口:"
    echo "    sudo ufw allow 18080/tcp   # HTTP API 端口"
    echo "    sudo ufw allow 35688/udp   # UDP 设备发现端口"
    echo "    sudo ufw reload"
}

# 启动服务
cmd_start() {
    get_install_dir "$1"
    
    local BIN_PATH="$INSTALL_DIR/bin/$APP_NAME"
    local CONFIG_PATH="$INSTALL_DIR/config/safesightd.json"
    local LOG_DIR="$INSTALL_DIR/logs"

    echo "========== 启动 SafeSight Control =========="
    echo "应用目录: $INSTALL_DIR"
    echo "配置文件: $CONFIG_PATH"
    echo ""

    # 检查二进制文件
    if [ ! -f "$BIN_PATH" ]; then
        echo -e "${RED}错误: 未找到二进制文件: $BIN_PATH${NC}"
        exit 1
    fi

    # 检查配置文件
    if [ ! -f "$CONFIG_PATH" ]; then
        echo -e "${RED}错误: 配置文件不存在: $CONFIG_PATH${NC}"
        exit 1
    fi

    # 验证 JSON 格式
    if command -v python3 &> /dev/null; then
        if ! python3 -m json.tool "$CONFIG_PATH" > /dev/null 2>&1; then
            echo -e "${RED}错误: 配置文件 JSON 格式不正确${NC}"
            exit 1
        fi
    fi

    # 创建日志目录
    if [ ! -d "$LOG_DIR" ]; then
        mkdir -p "$LOG_DIR" 2>/dev/null || {
            echo -e "${RED}错误: 无法创建日志目录: $LOG_DIR${NC}"
            echo "请检查权限或手动创建: sudo mkdir -p $LOG_DIR"
            exit 1
        }
    fi
    
    # 检查日志目录是否可写
    if [ ! -w "$LOG_DIR" ]; then
        echo -e "${RED}错误: 日志目录不可写: $LOG_DIR${NC}"
        echo "请修复权限: sudo chmod 755 $LOG_DIR"
        exit 1
    fi

    # 检查是否已在运行
    if [ -f "$PID_FILE" ]; then
        local PID=$(cat "$PID_FILE")
        if ps -p "$PID" > /dev/null 2>&1; then
            echo -e "${YELLOW}警告: $APP_NAME 已在运行 (PID: $PID)${NC}"
            exit 1
        else
            rm -f "$PID_FILE"
        fi
    fi

    # 启动服务
    echo "正在启动 $APP_NAME..."
    nohup "$BIN_PATH" "$CONFIG_PATH" >> "$LOG_DIR/$APP_NAME.log" 2>&1 &
    local PID=$!
    echo $PID > "$PID_FILE"

    # 等待启动
    sleep 2
    if ps -p "$PID" > /dev/null 2>&1; then
        echo ""
        echo -e "${GREEN}✅ 启动成功!${NC}"
        echo "   PID: $PID"
        echo "   日志: $LOG_DIR/$APP_NAME.log"
        echo ""
        echo "查看日志: tail -f $LOG_DIR/$APP_NAME.log"
    else
        echo ""
        echo -e "${RED}❌ 启动失败${NC}"
        echo ""
        echo "可能的错误原因:"
        echo "  1. 端口 18080 被占用"
        echo "  2. 配置文件格式错误"
        echo "  3. 权限不足"
        echo ""
        echo "尝试直接运行查看详细错误:"
        echo "  sudo $BIN_PATH $CONFIG_PATH"
        echo ""
        echo "或检查日志:"
        if [ -f "$LOG_DIR/$APP_NAME.log" ]; then
            echo "  tail -20 $LOG_DIR/$APP_NAME.log"
        fi
        rm -f "$PID_FILE"
        exit 1
    fi
}

# 停止服务
cmd_stop() {
    get_install_dir "$1"
    
    echo "========== 停止 SafeSight Control =========="

    if [ -f "$PID_FILE" ]; then
        local PID=$(cat "$PID_FILE")
        if ps -p "$PID" > /dev/null 2>&1; then
            echo "正在停止 $APP_NAME (PID: $PID)..."
            kill "$PID"
            
            echo -n "等待进程结束"
            for i in {1..10}; do
                if ! ps -p "$PID" > /dev/null 2>&1; then
                    echo ""
                    echo -e "${GREEN}✅ 已停止${NC}"
                    rm -f "$PID_FILE"
                    return 0
                fi
                echo -n "."
                sleep 1
            done
            echo ""
            
            echo "强制结束进程..."
            kill -9 "$PID" 2>/dev/null || true
            rm -f "$PID_FILE"
            echo -e "${GREEN}✅ 已强制停止${NC}"
        else
            echo -e "${YELLOW}ℹ️ 进程不存在 (PID: $PID)${NC}"
            rm -f "$PID_FILE"
        fi
    else
        # 尝试查找进程
        local PID=$(pgrep -f "^$INSTALL_DIR/bin/$APP_NAME" | head -1)
        if [ -n "$PID" ]; then
            echo "发现运行中的进程 (PID: $PID)，尝试停止..."
            kill "$PID" 2>/dev/null || true
            sleep 2
            if ! ps -p "$PID" > /dev/null 2>&1; then
                echo -e "${GREEN}✅ 已停止${NC}"
            else
                kill -9 "$PID" 2>/dev/null || true
                echo -e "${GREEN}✅ 已强制停止${NC}"
            fi
        else
            echo -e "${YELLOW}ℹ️ $APP_NAME 未在运行${NC}"
        fi
    fi
}

# 重启服务
cmd_restart() {
    cmd_stop "$@"
    sleep 1
    cmd_start "$@"
}

# 查看状态
cmd_status() {
    get_install_dir "$1"
    
    local BIN_PATH="$INSTALL_DIR/bin/$APP_NAME"
    local CONFIG_PATH="$INSTALL_DIR/config/safesightd.json"
    local LOG_DIR="$INSTALL_DIR/logs"

    echo "========== SafeSight Control 状态 =========="
    echo ""
    echo "基本信息:"
    echo "  应用目录: $INSTALL_DIR"
    echo "  二进制文件: $BIN_PATH"
    echo "  配置文件: $CONFIG_PATH"
    echo "  日志目录: $LOG_DIR"

    # 检查二进制文件
    if [ -f "$BIN_PATH" ]; then
        echo -e "  二进制状态: ${GREEN}✅ 存在${NC}"
    else
        echo -e "  二进制状态: ${RED}❌ 不存在${NC}"
    fi

    # 检查配置文件
    if [ -f "$CONFIG_PATH" ]; then
        echo -e "  配置文件: ${GREEN}✅ 存在${NC}"
        if command -v python3 &> /dev/null; then
            local LISTEN=$(python3 -c "import json; print(json.load(open('$CONFIG_PATH')).get('listen', 'N/A'))" 2>/dev/null)
            local DISCOVERY_PORT=$(python3 -c "import json; print(json.load(open('$CONFIG_PATH')).get('discovery_port', 'N/A'))" 2>/dev/null)
            echo "  监听地址: $LISTEN"
            echo "  发现端口: $DISCOVERY_PORT (UDP)"
        fi
    else
        echo -e "  配置文件: ${RED}❌ 不存在${NC}"
    fi

    echo ""
    echo "运行状态:"

    # 检查进程
    if [ -f "$PID_FILE" ]; then
        local PID=$(cat "$PID_FILE")
        if ps -p "$PID" > /dev/null 2>&1; then
            echo -e "  进程状态: ${GREEN}🟢 运行中${NC}"
            echo "  PID: $PID"
            
            if command -v ps &> /dev/null; then
                echo ""
                echo "进程详情:"
                ps -p "$PID" -o pid,pcpu,pmem,cmd --no-headers 2>/dev/null | while read line; do
                    echo "    $line"
                done
            fi
            
            echo ""
            echo "网络监听:"
            if command -v ss &> /dev/null; then
                ss -tlnp 2>/dev/null | grep "$PID" | head -3 | while read line; do
                    echo "    $line"
                done
            elif command -v netstat &> /dev/null; then
                netstat -tlnp 2>/dev/null | grep "$PID/" | head -3 | while read line; do
                    echo "    $line"
                done
            fi
            
            # API 测试
            if command -v curl &> /dev/null; then
                echo ""
                echo "API 测试:"
                local HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "http://127.0.0.1:18080/api/devices" 2>/dev/null || echo "000")
                if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "401" ]; then
                    echo -e "    ${GREEN}✅ HTTP API 响应正常 (HTTP $HTTP_CODE)${NC}"
                elif [ "$HTTP_CODE" = "000" ]; then
                    echo -e "    ${YELLOW}⚠️  无法连接 HTTP API${NC}"
                else
                    echo "    ℹ️  HTTP API 响应: $HTTP_CODE"
                fi
            fi
        else
            echo -e "  进程状态: ${RED}🔴 未运行 (PID 文件存在但进程不存在)${NC}"
        fi
    else
        local PID=$(pgrep -f "^$BIN_PATH" | head -1)
        if [ -n "$PID" ]; then
            echo -e "  进程状态: ${YELLOW}🟡 运行中 (无 PID 文件，PID: $PID)${NC}"
        else
            echo -e "  进程状态: ${BLUE}⚫ 未运行${NC}"
        fi
    fi

    # 日志信息
    echo ""
    echo "日志信息:"
    if [ -d "$LOG_DIR" ]; then
        local NEWEST_LOG=$(ls -t "$LOG_DIR"/*.log 2>/dev/null | head -1)
        if [ -n "$NEWEST_LOG" ]; then
            echo "  最新日志 ($NEWEST_LOG):"
            tail -n 3 "$NEWEST_LOG" | while read line; do
                echo "    $line"
            done
        else
            echo "  无日志文件"
        fi
    else
        echo "  日志目录不存在"
    fi
}

# 升级服务
cmd_upgrade() {
    check_root
    get_install_dir "$1"
    
    local SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
    local BACKUP_DIR="/root/3588admin-backup-$(date +%Y%m%d%H%M%S)"

    echo "========== SafeSight Control 升级 =========="
    echo "安装目录: $INSTALL_DIR"
    echo "备份目录: $BACKUP_DIR"
    echo ""

    # 检查安装目录是否存在
    if [ ! -d "$INSTALL_DIR" ]; then
        echo -e "${RED}错误: 安装目录不存在: $INSTALL_DIR${NC}"
        echo "请先运行安装命令"
        exit 1
    fi

    # 确认
    read -p "确定要升级 SafeSight Control? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "升级已取消"
        exit 0
    fi

    # 1. 停止服务
    echo "[1/5] 停止服务..."
    cmd_stop "$@" 2>/dev/null || true
    sleep 2

    # 2. 备份
    echo "[2/5] 备份现有数据..."
    mkdir -p "$BACKUP_DIR"
    
    if [ -f "$INSTALL_DIR/config/safesightd.json" ]; then
        cp "$INSTALL_DIR/config/safesightd.json" "$BACKUP_DIR/"
        echo "  已备份配置文件"
    fi
    
    if [ -d "$INSTALL_DIR/logs" ]; then
        cp -r "$INSTALL_DIR/logs" "$BACKUP_DIR/"
        echo "  已备份日志文件"
    fi
    
    if [ -f "$INSTALL_DIR/bin/safesightd" ]; then
        cp "$INSTALL_DIR/bin/safesightd" "$BACKUP_DIR/safesightd.old"
        echo "  已备份旧版本二进制"
    fi

    # 3. 更新二进制文件
    echo "[3/5] 更新二进制文件..."
    local BASE_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
    if [ -f "$BASE_DIR/bin/safesightd" ]; then
        cp "$BASE_DIR/bin/safesightd" "$INSTALL_DIR/bin/safesightd"
        chmod +x "$INSTALL_DIR/bin/safesightd"
        echo -e "  ${GREEN}已更新二进制文件${NC}"
    else
        echo -e "${YELLOW}警告: 未找到新的二进制文件${NC}"
    fi

    # 4. 更新脚本
    echo "[4/5] 更新脚本..."
    cp "$SCRIPT_DIR/3588admin" "$INSTALL_DIR/scripts/"
    chmod +x "$INSTALL_DIR/scripts/3588admin"
    echo "  已更新管理脚本"

    # 5. 启动服务
    echo "[5/5] 启动服务..."
    cmd_start "$@"

    echo ""
    echo -e "${GREEN}========== 升级完成 ==========${NC}"
    echo "备份位置: $BACKUP_DIR"
}

# 卸载服务
cmd_uninstall() {
    check_root
    get_install_dir "$1"

    echo "========== SafeSight Control 卸载 =========="
    echo "安装目录: $INSTALL_DIR"
    echo ""

    # 确认
    read -p "确定要完全卸载 SafeSight Control? 此操作不可恢复! (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "卸载已取消"
        exit 0
    fi

    # 1. 停止服务
    echo "[1/4] 停止服务..."
    cmd_stop "$@" 2>/dev/null || true

    # 停止 systemd 服务
    if systemctl is-active --quiet 3588admin 2>/dev/null; then
        systemctl stop 3588admin
    fi
    if systemctl is-enabled --quiet 3588admin 2>/dev/null; then
        systemctl disable 3588admin
    fi

    # 2. 删除 systemd 服务文件
    echo "[2/4] 删除 Systemd 服务..."
    if [ -f "/etc/systemd/system/3588admin.service" ]; then
        rm -f "/etc/systemd/system/3588admin.service"
        systemctl daemon-reload
        echo "  已删除 systemd 服务"
    fi

    # 3. 删除快捷方式
    echo "[3/4] 删除快捷方式..."
    rm -f /usr/local/bin/3588admin-start
    rm -f /usr/local/bin/3588admin-stop
    rm -f /usr/local/bin/3588admin-status
    rm -f /usr/local/bin/3588admin
    echo "  已删除命令快捷方式"

    # 4. 备份并删除安装目录
    echo "[4/4] 删除安装文件..."
    local BACKUP_DIR=""
    if [ -d "$INSTALL_DIR" ]; then
        if [ -f "$INSTALL_DIR/config/safesightd.json" ]; then
            BACKUP_DIR="/root/3588admin-backup-$(date +%Y%m%d%H%M%S)"
            mkdir -p "$BACKUP_DIR"
            cp "$INSTALL_DIR/config/safesightd.json" "$BACKUP_DIR/"
            echo "  配置已备份到: $BACKUP_DIR/"
        fi
        
        rm -rf "$INSTALL_DIR"
        echo "  已删除安装目录: $INSTALL_DIR"
    fi

    echo ""
    echo -e "${GREEN}========== 卸载完成 ==========${NC}"
    if [ -n "$BACKUP_DIR" ]; then
        echo "配置文件备份: $BACKUP_DIR/safesightd.json"
    fi
}

# 主函数
main() {
    # 如果没有参数，显示帮助
    if [ $# -eq 0 ]; then
        cmd_help
        exit 0
    fi

    # 解析命令
    COMMAND="$1"
    shift

    case "$COMMAND" in
        install)
            cmd_install "$@"
            ;;
        status)
            cmd_status "$@"
            ;;
        start)
            cmd_start "$@"
            ;;
        stop)
            cmd_stop "$@"
            ;;
        restart)
            cmd_restart "$@"
            ;;
        upgrade)
            cmd_upgrade "$@"
            ;;
        uninstall)
            cmd_uninstall "$@"
            ;;
        check)
            cmd_check "$@"
            ;;
        help|--help|-h)
            cmd_help
            ;;
        *)
            # 兼容快捷方式调用
            # 如果是通过快捷方式调用，脚本名就是命令
            SCRIPT_NAME=$(basename "$0")
            case "$SCRIPT_NAME" in
                3588admin-start)
                    cmd_start "$@"
                    ;;
                3588admin-stop)
                    cmd_stop "$@"
                    ;;
                3588admin-status)
                    cmd_status "$@"
                    ;;
                *)
                    echo -e "${RED}错误: 未知命令 '$COMMAND'${NC}"
                    echo ""
                    cmd_help
                    exit 1
                    ;;
            esac
            ;;
    esac
}

main "$@"
