#!/bin/bash

# Edge 边缘节点完整安装脚本
# 使用方法: ./install_edge.sh <中控服务器IP>

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

# 下载地址配置
DOWNLOAD_URLS=(
    "http://43.133.77.111/downloads/generator.tar.gz"
    "http://43.133.77.111/downloads/node.tar.gz"
    "http://43.133.77.111/downloads/srs.tar.gz"
    "http://43.133.77.111/downloads/streammonitor.tar.gz"
    "http://43.133.77.111/downloads/monitor.tar.gz"
    "http://43.133.77.111/downloads/udpserver.tar.gz"
    "http://43.133.77.111/downloads/logstash.tar.gz"
    "http://43.133.77.111/downloads/srslimit.tar.gz"
)

# 服务名称配置
SERVICE_NAMES=(
    "generator"
    "node"
    "srs"
    "streammonitor"
    "monitor"
    "udpserver"
    "logstash"
    "srslimit"
)

# 服务配置（是否需要IP参数）
SERVICE_NEEDS_IP=(
    true    # generator
    true    # node
    true    # srs
    false   # streammonitor
    false   # monitor
    false   # udpserver
    true    # logstash
    false   # srslimit
)

# 安装结果记录
INSTALL_RESULTS=()
SERVICE_STATUS=()
SKIPPED_SERVICES=()

# 验证服务名称
validate_service_name() {
    local service_name="$1"
    
    for service in "${SERVICE_NAMES[@]}"; do
        if [ "$service" = "$service_name" ]; then
            return 0
        fi
    done
    
    return 1
}

# 设置系统 ulimit 参数
setup_ulimit() {
    echo -e "${BLUE}🔧 正在设置系统 ulimit 参数...${NC}"
    
    # 检查当前 ulimit -n 值
    local current_limit=$(ulimit -n 2>/dev/null || echo "unknown")
    echo -e "${BLUE}当前文件描述符限制: ${current_limit}${NC}"
    
    # 尝试设置当前会话的 ulimit
    if ulimit -n 65535 2>/dev/null; then
        echo -e "${GREEN}✅ 当前会话 ulimit -n 已设置为 65535${NC}"
    else
        echo -e "${YELLOW}⚠️  无法设置当前会话 ulimit -n，需要 root 权限${NC}"
    fi
    
    # 永久设置 ulimit（通过配置文件）
    echo -e "${BLUE}正在永久设置 ulimit 参数...${NC}"
    
    # 方法1: 通过 /etc/security/limits.conf
    local limits_conf="/etc/security/limits.conf"
    if [ -w "$limits_conf" ]; then
        # 备份原文件
        if [ ! -f "${limits_conf}.bak" ]; then
            cp "$limits_conf" "${limits_conf}.bak"
            echo -e "${BLUE}已备份 ${limits_conf} 到 ${limits_conf}.bak${NC}"
        fi
        
        # 检查是否已经设置
        if ! grep -q "^\\*.*soft.*nofile.*65535" "$limits_conf"; then
            # 添加配置行
            echo "" >> "$limits_conf"
            echo "# Edge 边缘节点文件描述符限制设置" >> "$limits_conf"
            echo "* soft nofile 65535" >> "$limits_conf"
            echo "* hard nofile 65535" >> "$limits_conf"
            echo "root soft nofile 65535" >> "$limits_conf"
            echo "root hard nofile 65535" >> "$limits_conf"
            echo -e "${GREEN}✅ 已在 ${limits_conf} 中添加 ulimit 配置${NC}"
        else
            echo -e "${GREEN}✅ ${limits_conf} 中已存在 ulimit 配置${NC}"
        fi
    else
        echo -e "${YELLOW}⚠️  无法写入 ${limits_conf}，需要 root 权限${NC}"
    fi
    
    # 方法2: 通过 /etc/systemd/system.conf (如果使用 systemd)
    local systemd_conf="/etc/systemd/system.conf"
    if [ -w "$systemd_conf" ]; then
        # 检查是否已经设置
        if ! grep -q "^#DefaultLimitNOFILE=" "$systemd_conf" || ! grep -q "^DefaultLimitNOFILE=" "$systemd_conf"; then
            # 备份原文件
            if [ ! -f "${systemd_conf}.bak" ]; then
                cp "$systemd_conf" "${systemd_conf}.bak"
                echo -e "${BLUE}已备份 ${systemd_conf} 到 ${systemd_conf}.bak${NC}"
            fi
            
            # 添加配置
            echo "" >> "$systemd_conf"
            echo "# Edge 边缘节点文件描述符限制设置" >> "$systemd_conf"
            echo "DefaultLimitNOFILE=65535" >> "$systemd_conf"
            echo -e "${GREEN}✅ 已在 ${systemd_conf} 中添加 ulimit 配置${NC}"
        else
            echo -e "${GREEN}✅ ${systemd_conf} 中已存在 ulimit 配置${NC}"
        fi
    else
        echo -e "${YELLOW}⚠️  无法写入 ${systemd_conf}，需要 root 权限${NC}"
    fi
    
    # 方法3: 通过 /etc/profile 或 ~/.bashrc
    local profile_file="/etc/profile"
    if [ -w "$profile_file" ]; then
        # 检查是否已经设置
        if ! grep -q "ulimit -n 65535" "$profile_file"; then
            # 备份原文件
            if [ ! -f "${profile_file}.bak" ]; then
                cp "$profile_file" "${profile_file}.bak"
                echo -e "${BLUE}已备份 ${profile_file} 到 ${profile_file}.bak${NC}"
            fi
            
            # 添加配置
            echo "" >> "$profile_file"
            echo "# Edge 边缘节点文件描述符限制设置" >> "$profile_file"
            echo "ulimit -n 65535" >> "$profile_file"
            echo -e "${GREEN}✅ 已在 ${profile_file} 中添加 ulimit 配置${NC}"
        else
            echo -e "${GREEN}✅ ${profile_file} 中已存在 ulimit 配置${NC}"
        fi
    else
        echo -e "${YELLOW}⚠️  无法写入 ${profile_file}，需要 root 权限${NC}"
    fi
    
    # 设置系统 sysctl 参数
    echo -e "${BLUE}🔧 正在设置系统 sysctl 网络参数...${NC}"
    local sysctl_conf="/etc/sysctl.conf"
    if [ -w "$sysctl_conf" ]; then
        # 备份原文件
        if [ ! -f "${sysctl_conf}.bak" ]; then
            cp "$sysctl_conf" "${sysctl_conf}.bak"
            echo -e "${BLUE}已备份 ${sysctl_conf} 到 ${sysctl_conf}.bak${NC}"
        fi
        
        # 检查是否已经设置过这些参数
        if ! grep -q "^net.ipv4.tcp_syncookies = 1" "$sysctl_conf"; then
            # 添加配置到文件末尾
            echo "" >> "$sysctl_conf"
            echo "# Edge 边缘节点网络参数设置" >> "$sysctl_conf"
            echo "net.ipv4.tcp_syncookies = 1" >> "$sysctl_conf"
            echo "net.ipv4.tcp_tw_reuse = 1" >> "$sysctl_conf"
            echo "net.ipv4.tcp_tw_recycle = 1" >> "$sysctl_conf"
            echo "net.ipv4.tcp_fin_timeout = 30" >> "$sysctl_conf"
            echo "net.ipv4.tcp_max_tw_buckets = 5000" >> "$sysctl_conf"
            echo "net.ipv4.tcp_max_syn_backlog = 1024" >> "$sysctl_conf"
            echo "net.ipv4.tcp_synack_retries = 2" >> "$sysctl_conf"
            echo "net.ipv4.tcp_slow_start_after_idle = 0" >> "$sysctl_conf"
            echo "" >> "$sysctl_conf"
            echo "net.core.rmem_max=26214400 # BDP - bandwidth delay product" >> "$sysctl_conf"
            echo "net.core.rmem_default=26214400" >> "$sysctl_conf"
            echo "net.core.wmem_max=26214400" >> "$sysctl_conf"
            echo "net.core.wmem_default=26214400" >> "$sysctl_conf"
            echo "net.core.netdev_max_backlog=2048 # proportional to -rcvwnd" >> "$sysctl_conf"
            echo -e "${GREEN}✅ 已在 ${sysctl_conf} 中添加网络参数配置${NC}"
            
            # 执行 sysctl -p 使配置生效
            echo -e "${BLUE}正在应用 sysctl 配置...${NC}"
            if sysctl -p > /dev/null 2>&1; then
                echo -e "${GREEN}✅ sysctl 配置已成功应用${NC}"
            else
                echo -e "${YELLOW}⚠️  sysctl -p 执行时出现警告，但配置已写入文件${NC}"
            fi
        else
            echo -e "${GREEN}✅ ${sysctl_conf} 中已存在网络参数配置${NC}"
            # 即使已存在，也尝试应用配置
            if sysctl -p > /dev/null 2>&1; then
                echo -e "${GREEN}✅ sysctl 配置已重新应用${NC}"
            fi
        fi
    else
        echo -e "${YELLOW}⚠️  无法写入 ${sysctl_conf}，需要 root 权限${NC}"
    fi
    
    # 显示设置结果
    echo ""
    echo -e "${GREEN}═══════════════════════════════════════════════════════════════${NC}"
    echo -e "${GREEN}📋 ulimit 设置完成${NC}"
    echo -e "${GREEN}═══════════════════════════════════════════════════════════════${NC}"
    echo -e "${GREEN}✅ 文件描述符限制已永久设置为 65535${NC}"
    echo -e "${GREEN}✅ 配置已写入系统配置文件${NC}"
    echo -e "${GREEN}✅ 重启后生效，或执行 'source /etc/profile' 立即生效${NC}"
    echo -e "${GREEN}═══════════════════════════════════════════════════════════════${NC}"
    echo ""
}

# 显示帮助信息
show_help() {
    echo -e "${BLUE}Edge 边缘节点完整安装脚本${NC}"
    echo ""
    echo "使用方法:"
echo "  $0 <中控服务器IP> [选项]"
echo "  $0 <中控服务器IP> <服务名称>      # 重新安装指定服务"
echo ""
echo "示例:"
echo "  $0 51.79.20.189                    # 交互模式：询问是否跳过已安装的服务"
echo "  $0 51.79.20.189 --auto-skip        # 自动跳过模式：自动跳过已安装且运行正常的服务"
echo "  $0 51.79.20.189 --force-reinstall  # 强制重装模式：重新安装所有服务"
echo "  $0 51.79.20.189 generator          # 重新安装 generator 服务"
echo "  $0 51.79.20.189 srs                # 重新安装 srs 服务"
    echo ""
    echo "选项说明:"
    echo "  --auto-skip        自动跳过已安装且运行正常的服务"
    echo "  --force-reinstall  强制重新安装所有服务"
    echo "  --help, -h         显示此帮助信息"
    echo ""
    echo "功能说明:"
    echo "  1. 自动安装所有边缘节点服务（8个服务）"
    echo "  2. 支持IP参数验证和配置"
    echo "  3. 智能跳过已安装的服务，避免重复安装"
    echo "  4. 显示详细的安装进度和结果"
    echo "  5. 标识安装失败和启动失败的服务"
    echo "  6. 自动设置系统 ulimit -n 为 65535（永久生效）"
    echo ""
    echo "包含的服务:"
    echo "  - generator, node, srs, logstash (需要中控服务器IP)"
    echo "  - streammonitor, monitor, udpserver, srslimit (无需IP参数)"
    echo ""
    echo "智能安装特性:"
    echo "  - 自动检测已安装的服务"
    echo "  - 智能跳过运行正常的服务"
    echo "  - 支持多种安装模式"
    echo "  - 避免重复安装和配置"
}

# 检查参数
if [ $# -eq 0 ]; then
    echo -e "${RED}错误: 必须提供中控服务器IP地址参数${NC}"
    echo ""
    show_help
    exit 1
fi

# 解析额外参数
AUTO_SKIP=false
FORCE_REINSTALL=false
SINGLE_SERVICE=""

while [[ $# -gt 0 ]]; do
    case $1 in
        --auto-skip)
            AUTO_SKIP=true
            shift
            ;;
        --force-reinstall)
            FORCE_REINSTALL=true
            shift
            ;;
        --help|-h)
            show_help
            exit 0
            ;;
        *)
            if [[ -z "$CONTROL_IP" ]]; then
                CONTROL_IP="$1"
            elif [[ -z "$SINGLE_SERVICE" ]]; then
                SINGLE_SERVICE="$1"
            else
                echo -e "${RED}错误: 未知参数 $1${NC}"
                show_help
                exit 1
            fi
            shift
            ;;
    esac
done

# 验证IP地址格式
if [[ -z "$CONTROL_IP" ]]; then
    echo -e "${RED}错误: 必须提供中控服务器IP地址参数${NC}"
    echo ""
    show_help
    exit 1
fi

if [[ ! "$CONTROL_IP" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    echo -e "${RED}错误: 无效的IP地址格式${NC}"
    echo "请提供有效的IPv4地址，例如: 51.79.20.189"
    exit 1
fi

echo -e "${GREEN}使用中控服务器IP: ${CONTROL_IP}${NC}"

# 如果指定了单个服务，验证服务名称
if [ -n "$SINGLE_SERVICE" ]; then
    if ! validate_service_name "$SINGLE_SERVICE"; then
        echo -e "${RED}错误: 无效的服务名称 '${SINGLE_SERVICE}'${NC}"
        echo -e "${BLUE}支持的服务名称: ${SERVICE_NAMES[*]}${NC}"
        exit 1
    fi
    echo -e "${GREEN}指定重新安装服务: ${SINGLE_SERVICE}${NC}"
fi

if [ "$AUTO_SKIP" = true ]; then
    echo -e "${YELLOW}自动跳过模式: 已安装且运行正常的服务将被自动跳过${NC}"
fi
if [ "$FORCE_REINSTALL" = true ]; then
    echo -e "${YELLOW}强制重装模式: 所有服务都将重新安装${NC}"
fi
echo ""

# 创建临时目录
TEMP_DIR="/tmp/edge_install_$(date +%s)"
echo -e "${BLUE}正在创建临时目录: ${TEMP_DIR}${NC}"
mkdir -p "$TEMP_DIR"
cd "$TEMP_DIR"

# 设置系统 ulimit 参数
setup_ulimit

echo ""

# 安装单个服务的函数
install_service() {
    local service_index=$1
    local service_name=${SERVICE_NAMES[$service_index]}
    local download_url=${DOWNLOAD_URLS[$service_index]}
    local needs_ip=${SERVICE_NEEDS_IP[$service_index]}
    
    echo -e "${BLUE}═══════════════════════════════════════════════════════════════${NC}"
    echo -e "${BLUE}🚀 开始安装 ${service_name} 服务${NC}"
    echo -e "${BLUE}═══════════════════════════════════════════════════════════════${NC}"
    echo ""
    
    # 检查服务是否已经安装并运行正常
    echo -e "${BLUE}🔍 检查 ${service_name} 服务状态...${NC}"
    local service_already_installed=false
    local service_running=false
    
    # 检查服务目录是否存在
    if [ -d "/sce/${service_name}" ] || [ -d "/sce/${service_name}-9.0.1" ]; then
        service_already_installed=true
        echo -e "${YELLOW}⚠️  ${service_name} 服务目录已存在${NC}"
        
        # 检查 supervisor 服务状态
        if command -v supervisorctl &>/dev/null; then
            local service_status=$(supervisorctl status "$service_name" 2>/dev/null | grep -o "RUNNING\|STOPPED\|STARTING\|STOPPING\|EXITED\|FATAL\|UNKNOWN")
            if [ "$service_status" = "RUNNING" ]; then
                service_running=true
                echo -e "${GREEN}✅ ${service_name} 服务正在运行${NC}"
            else
                echo -e "${YELLOW}⚠️  ${service_name} 服务未运行，状态: ${service_status}${NC}"
            fi
        else
            echo -e "${YELLOW}⚠️  supervisor 未安装，无法检查服务状态${NC}"
        fi
        
        # 如果服务已安装且正在运行，根据模式决定是否跳过
        if [ "$service_already_installed" = true ] && [ "$service_running" = true ]; then
            echo -e "${GREEN}🎯 ${service_name} 服务已安装并运行正常${NC}"
            
            if [ "$FORCE_REINSTALL" = true ]; then
                echo -e "${YELLOW}🔄 强制重装模式: 继续安装 ${service_name} 服务${NC}"
            elif [ "$AUTO_SKIP" = true ]; then
                echo -e "${GREEN}⏭️  自动跳过模式: 跳过 ${service_name} 服务安装${NC}"
                INSTALL_RESULTS[$service_index]=0
                SERVICE_STATUS[$service_index]=0
                SKIPPED_SERVICES[$service_index]=1
                echo ""
                return 0
            else
                # 交互模式：询问用户是否跳过
                echo -e "${YELLOW}是否跳过安装？(y/N): ${NC}"
                read -r skip_install
                if [[ "$skip_install" =~ ^[Yy]$ ]]; then
                    echo -e "${GREEN}⏭️  跳过 ${service_name} 服务安装${NC}"
                    INSTALL_RESULTS[$service_index]=0
                    SERVICE_STATUS[$service_index]=0
                    SKIPPED_SERVICES[$service_index]=1
                    echo ""
                    return 0
                else
                    echo -e "${BLUE}🔄 继续安装 ${service_name} 服务${NC}"
                fi
            fi
        fi
    else
        echo -e "${BLUE}📦 ${service_name} 服务未安装，开始安装...${NC}"
    fi
    
    echo ""
    
    # 创建服务临时目录
    local service_temp_dir="${TEMP_DIR}/${service_name}_install"
    mkdir -p "$service_temp_dir"
    cd "$service_temp_dir"
    
    # 下载服务包
    echo -e "${BLUE}正在从 ${download_url} 下载 ${service_name}.tar.gz...${NC}"
    if command -v wget &>/dev/null; then
        wget -q --show-progress "$download_url"
    elif command -v curl &>/dev/null; then
        curl -L -o "${service_name}.tar.gz" "$download_url"
    else
        echo -e "${RED}错误: 未找到 wget 或 curl 命令${NC}"
        return 1
    fi
    
    # 检查下载是否成功
    if [ ! -f "${service_name}.tar.gz" ]; then
        echo -e "${RED}❌ 下载失败: ${service_name}.tar.gz${NC}"
        return 1
    fi
    
    echo -e "${GREEN}✅ 下载完成${NC}"
    
    # 解压文件
    echo -e "${BLUE}正在解压 ${service_name}.tar.gz...${NC}"
    tar -xzf "${service_name}.tar.gz"
    
    if [ $? -ne 0 ]; then
        echo -e "${RED}❌ 解压失败: ${service_name}${NC}"
        return 1
    fi
    
    echo -e "${GREEN}✅ 解压完成${NC}"
    
    # 检查解压后的目录结构
    if [ ! -d "$service_name" ]; then
        echo -e "${RED}❌ 解压后未找到 ${service_name} 目录${NC}"
        return 1
    fi
    
    if [ ! -f "$service_name/install.sh" ]; then
        echo -e "${RED}❌ 未找到 ${service_name}/install.sh 脚本${NC}"
        return 1
    fi
    
    echo -e "${GREEN}✅ 文件结构验证通过${NC}"
    
    # 给 install.sh 添加执行权限
    chmod +x "$service_name/install.sh"
    
    # 调用 install.sh 进行安装
    echo -e "${BLUE}正在调用 ${service_name}/install.sh 进行安装...${NC}"
    echo -e "${YELLOW}注意: 安装过程可能需要几分钟，请耐心等待...${NC}"
    echo ""
    
    cd "$service_name"
    
    # 根据是否需要IP参数调用安装脚本
    if [ "$needs_ip" = true ]; then
        ./install.sh "$CONTROL_IP"
    else
        ./install.sh
    fi
    
    local install_result=$?
    
    # 返回服务临时目录
    cd "$service_temp_dir"
    
    # 记录安装结果
    if [ $install_result -eq 0 ]; then
        echo -e "${GREEN}🎉 ${service_name} 安装完成！${NC}"
        INSTALL_RESULTS[$service_index]=0
        
        # 检查服务状态
        if command -v supervisorctl &>/dev/null; then
            local service_status=$(supervisorctl status "$service_name" 2>/dev/null | grep -o "RUNNING\|STOPPED\|STARTING\|STOPPING\|EXITED\|FATAL\|UNKNOWN")
            if [ "$service_status" = "RUNNING" ]; then
                echo -e "${GREEN}✅ ${service_name} 服务运行正常${NC}"
                SERVICE_STATUS[$service_index]=0
            else
                echo -e "${RED}❌ ${service_name} 服务启动失败，状态: ${service_status}${NC}"
                SERVICE_STATUS[$service_index]=1
            fi
        else
            echo -e "${YELLOW}⚠️  无法检查 ${service_name} 服务状态（supervisor未安装）${NC}"
            SERVICE_STATUS[$service_index]=2
        fi
    else
        echo -e "${RED}❌ ${service_name} 安装失败，退出码: $install_result${NC}"
        INSTALL_RESULTS[$service_index]=1
        SERVICE_STATUS[$service_index]=1
    fi
    
    echo ""
    
    # 返回主临时目录
    cd "$TEMP_DIR"
}

# 主安装流程
if [ -n "$SINGLE_SERVICE" ]; then
    # 单个服务安装模式
    echo -e "${GREEN}🎯 开始重新安装单个服务${NC}"
    echo -e "${GREEN}目标IP: ${CONTROL_IP}${NC}"
    echo -e "${GREEN}目标服务: ${SINGLE_SERVICE}${NC}"
    echo ""
    
    # 查找服务索引
    service_index=-1
    for i in "${!SERVICE_NAMES[@]}"; do
        if [ "${SERVICE_NAMES[$i]}" = "$SINGLE_SERVICE" ]; then
            service_index=$i
            break
        fi
    done
    
    if [ $service_index -eq -1 ]; then
        echo -e "${RED}错误: 未找到服务 ${SINGLE_SERVICE}${NC}"
        exit 1
    fi
    
    # 强制重新安装模式
    FORCE_REINSTALL=true
    echo -e "${YELLOW}🔄 强制重新安装模式: 将重新安装 ${SINGLE_SERVICE} 服务${NC}"
    echo ""
    
    # 安装指定服务
    install_service $service_index
    echo ""
    
    # 显示单个服务安装结果
    service_name=${SERVICE_NAMES[$service_index]}
    install_result=${INSTALL_RESULTS[$service_index]}
    service_status=${SERVICE_STATUS[$service_index]}
    
    # 初始化统计变量（单个服务模式）
    install_success=0
    install_failed=0
    service_success=0
    service_failed=0
    
    echo -e "${GREEN}═══════════════════════════════════════════════════════════════${NC}"
    echo -e "${GREEN}🎯 单个服务安装结果${NC}"
    echo -e "${GREEN}═══════════════════════════════════════════════════════════════${NC}"
    echo ""
    
    if [ "${install_result:-1}" -eq 0 ]; then
        echo -e "${GREEN}✅ ${service_name}: 安装成功${NC}"
        if [ "${service_status:-1}" -eq 0 ]; then
            echo -e "${GREEN}✅ ${service_name}: 服务运行正常${NC}"
        else
            echo -e "${RED}❌ ${service_name}: 服务启动失败${NC}"
        fi
    else
        echo -e "${RED}❌ ${service_name}: 安装失败${NC}"
    fi
    
    echo ""
    echo -e "${GREEN}═══════════════════════════════════════════════════════════════${NC}"
    echo -e "${GREEN}🎯 单个服务安装完成${NC}"
    echo -e "${GREEN}═══════════════════════════════════════════════════════════════${NC}"
    echo -e "${GREEN}中控服务器IP: ${CONTROL_IP}${NC}"
    echo -e "${GREEN}安装时间: $(date)${NC}"
    echo -e "${GREEN}临时目录: ${TEMP_DIR} (已清理)${NC}"
    echo ""
    
    # 清理临时文件
    echo -e "${BLUE}正在清理临时文件...${NC}"
    cd /
    rm -rf "$TEMP_DIR"
    echo -e "${GREEN}✅ 临时文件清理完成${NC}"
    
    # 返回适当的退出码
    if [ "${install_result:-1}" -eq 0 ] && [ "${service_status:-1}" -eq 0 ]; then
        echo -e "${GREEN}✅ 服务安装成功！${NC}"
        exit 0
    else
        echo -e "${RED}⚠️  服务存在问题，请查看上述详细信息${NC}"
        exit 1
    fi
else
    # 完整安装模式
    echo -e "${GREEN}🎯 开始安装 Edge 边缘节点所有服务${NC}"
    echo -e "${GREEN}目标IP: ${CONTROL_IP}${NC}"
    echo -e "${GREEN}服务数量: ${#SERVICE_NAMES[@]}${NC}"
    echo ""
    
    # 安装所有服务
    for i in "${!SERVICE_NAMES[@]}"; do
        install_service $i
        echo ""
    done
fi

# 显示安装总结
echo -e "${GREEN}═══════════════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}🎯 Edge 边缘节点安装总结${NC}"
echo -e "${GREEN}═══════════════════════════════════════════════════════════════${NC}"
echo ""

# 统计安装结果
install_success=0
install_failed=0
service_success=0
service_failed=0
skipped_count=0

for i in "${!SERVICE_NAMES[@]}"; do
    service_name=${SERVICE_NAMES[$i]}
    install_result=${INSTALL_RESULTS[$i]}
    service_status=${SERVICE_STATUS[$i]}
    was_skipped=${SKIPPED_SERVICES[$i]:-0}
    
    if [ $was_skipped -eq 1 ]; then
        skipped_count=$((skipped_count + 1))
        echo -e "${BLUE}⏭️  ${service_name}: 跳过安装（已安装且运行正常）${NC}"
    elif [ $install_result -eq 0 ]; then
        install_success=$((install_success + 1))
        if [ $service_status -eq 0 ]; then
            service_success=$((service_success + 1))
            echo -e "${GREEN}✅ ${service_name}: 安装成功，服务运行正常${NC}"
        else
            service_failed=$((service_failed + 1))
            echo -e "${RED}❌ ${service_name}: 安装成功，但服务启动失败${NC}"
        fi
    else
        install_failed=$((install_failed + 1))
        echo -e "${RED}❌ ${service_name}: 安装失败${NC}"
    fi
done

echo ""
echo -e "${GREEN}═══════════════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}📊 安装统计${NC}"
echo -e "${GREEN}═══════════════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}总服务数: ${#SERVICE_NAMES[@]}${NC}"
if [ "${skipped_count:-0}" -gt 0 ]; then
    echo -e "${BLUE}跳过安装: ${skipped_count}${NC}"
fi
echo -e "${GREEN}安装成功: ${install_success}${NC}"
echo -e "${GREEN}安装失败: ${install_failed}${NC}"
echo -e "${GREEN}服务运行: ${service_success}${NC}"
echo -e "${GREEN}服务异常: ${service_failed}${NC}"
echo ""

# 显示失败服务详情
if [ "${install_failed:-0}" -gt 0 ] || [ "${service_failed:-0}" -gt 0 ]; then
    echo -e "${RED}═══════════════════════════════════════════════════════════════${NC}"
    echo -e "${RED}🚨 需要关注的服务${NC}"
    echo -e "${RED}═══════════════════════════════════════════════════════════════${NC}"
    echo ""
    
    # 安装失败的服务
    if [ "${install_failed:-0}" -gt 0 ]; then
        echo -e "${RED}📦 安装失败的服务:${NC}"
        for i in "${!SERVICE_NAMES[@]}"; do
            if [ ${INSTALL_RESULTS[$i]} -ne 0 ]; then
                echo -e "${RED}   ❌ ${SERVICE_NAMES[$i]}${NC}"
            fi
        done
        echo ""
    fi
    
    # 启动失败的服务
    if [ "${service_failed:-0}" -gt 0 ]; then
        echo -e "${RED}🚀 启动失败的服务:${NC}"
        for i in "${!SERVICE_NAMES[@]}"; do
            if [ ${INSTALL_RESULTS[$i]} -eq 0 ] && [ ${SERVICE_STATUS[$i]} -eq 1 ]; then
                echo -e "${RED}   ❌ ${SERVICE_NAMES[$i]}${NC}"
            fi
        done
        echo ""
    fi
    
    echo -e "${RED}建议操作:${NC}"
    echo -e "${RED}1. 检查失败服务的日志文件${NC}"
    echo -e "${RED}2. 检查系统资源和权限${NC}"
    echo -e "${RED}3. 重新运行安装脚本${NC}"
    echo -e "${RED}4. 联系技术支持${NC}"
    echo ""
fi

# 显示成功信息
if [ "${install_failed:-0}" -eq 0 ] && [ "${service_failed:-0}" -eq 0 ]; then
    echo -e "${GREEN}🎉 恭喜！所有服务安装成功并运行正常！${NC}"
    echo -e "${GREEN}Edge 边缘节点已完全部署完成！${NC}"
    echo ""
fi

# 清理临时文件
echo -e "${BLUE}正在清理临时文件...${NC}"
cd /
rm -rf "$TEMP_DIR"
echo -e "${GREEN}✅ 临时文件清理完成${NC}"

echo ""
echo -e "${GREEN}═══════════════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}🎯 Edge 边缘节点安装完成${NC}"
echo -e "${GREEN}═══════════════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}中控服务器IP: ${CONTROL_IP}${NC}"
echo -e "${GREEN}安装时间: $(date)${NC}"
echo -e "${GREEN}临时目录: ${TEMP_DIR} (已清理)${NC}"
echo ""

# 返回适当的退出码
if [ "${install_failed:-0}" -gt 0 ] || [ "${service_failed:-0}" -gt 0 ]; then
    echo -e "${RED}⚠️  部分服务存在问题，请查看上述详细信息${NC}"
    exit 1
else
    echo -e "${GREEN}✅ 所有服务安装成功！${NC}"
    exit 0
fi
