#!/bin/bash
################################################################################
# EMQX深度检测模块
# 功能: 深度检测EMQX连接、订阅、消息统计、集群、性能等
# 作者: Claude Code
# 日期: 2026-07-20
################################################################################

# 获取脚本所在目录并加载依赖
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LIB_DIR="${LIB_DIR:-/tmp/check_modules}"

# 加载配置文件和通用函数库
if [ -f "$LIB_DIR/lib/config.sh" ]; then
    source "$LIB_DIR/lib/config.sh"
else
    echo "ERROR: 配置文件不存在: $LIB_DIR/lib/config.sh"
    exit 1
fi

if [ -f "$LIB_DIR/lib/common.sh" ]; then
    source "$LIB_DIR/lib/common.sh"
else
    echo "ERROR: 通用函数库不存在: $LIB_DIR/lib/common.sh"
    exit 1
fi

# EMQX容器名称
EMQX_CONTAINER="${CONTAINERS[emqx]}"

# ==================== 辅助函数 ====================

# 在EMQX容器中执行命令
emqx_exec() {
    docker exec "$EMQX_CONTAINER" $@ 2>/dev/null
}

# ==================== 深度检测函数 ====================

# 检测EMQX详细状态
check_emqx_status_detail() {
    local broker_status node_status

    broker_status=$(emqx_exec emqx_ctl broker 2>/dev/null)
    node_status=$(emqx_exec emqx_ctl status 2>/dev/null)

    if [ -n "$broker_status" ]; then
        # 提取版本信息
        local version
        version=$(echo "$broker_status" | grep -i "version" | head -1 | awk '{for(i=2;i<=NF;i++)printf $i" "}')

        if [ -n "$version" ]; then
            output_result "EMQX_BROKER_VERSION" "$version"
        fi
    fi

    if [ -n "$node_status" ]; then
        output_result "EMQX_NODE_STATUS" "运行中"
        output_result "EMQX_NODE_LEVEL" "正常"
    fi
}

# 检测EMQX客户端详情
check_emqx_clients_detail() {
    # 获取客户端总数
    local client_count
    client_count=$(emqx_exec emqx_ctl clients list 2>/dev/null | wc -l)

    if [ -n "$client_count" ]; then
        output_result "EMQX_CLIENTS_TOTAL" "$client_count"
    fi

    # 获取连接状态统计
    local clients_connected clients_disconnected
    clients_connected=$(emqx_exec emqx_ctl clients list 2>/dev/null | grep -c "connected" || echo "0")

    if [ -n "$clients_connected" ]; then
        output_result "EMQX_CLIENTS_CONNECTED" "$clients_connected"
        clients_disconnected=$((client_count - clients_connected))
        output_result "EMQX_CLIENTS_DISCONNECTED" "$clients_disconnected"
    fi

    # 获取最大客户端连接数配置
    local max_clients_config
    max_clients_config=$(emqx_exec emqx_ctl listeners list 2>/dev/null | grep -E "max_connections" | awk '{print $NF}' | head -1)

    if [ -z "$max_clients_config" ] || [ "$max_clients_config" = "0" ]; then
        max_clients_config="infinity"
    fi

    if [ -n "$max_clients_config" ]; then
        output_result "EMQX_MAX_CLIENTS" "$max_clients_config"
    fi
}

# 检测EMQX订阅详情
check_emqx_subscriptions_detail() {
    # 获取订阅总数
    local sub_count
    sub_count=$(emqx_exec emqx_ctl subscriptions list 2>/dev/null | wc -l)

    if [ -n "$sub_count" ]; then
        output_result "EMQX_SUBSCRIPTIONS_TOTAL" "$sub_count"
    fi

    # 统计各主题订阅数
    local top_topics
    top_topics=$(emqx_exec emqx_ctl subscriptions list 2>/dev/null | awk '{print $2}' | sort | uniq -c | sort -rn | head -5 | tr '\n' '|' | sed 's/|$//')

    if [ -n "$top_topics" ]; then
        output_result "EMQX_TOP_TOPICS" "$top_topics"
    fi
}

# 检测EMQX消息统计
check_emqx_messages_stats() {
    # 获取消息统计
    local messages_stats
    messages_stats=$(emqx_exec emqx_ctl metrics 2>/dev/null | grep -E "messages" || echo "")

    if [ -n "$messages_stats" ]; then
        # 提取关键指标
        local messages_sent messages_received
        messages_sent=$(echo "$messages_stats" | grep "messages.sent" | awk '{print $2}' || echo "0")
        messages_received=$(echo "$messages_stats" | grep "messages.received" | awk '{print $2}' || echo "0")

        if [ -n "$messages_sent" ]; then
            output_result "EMQX_MESSAGES_SENT" "$messages_sent"
        fi

        if [ -n "$messages_received" ]; then
            output_result "EMQX_MESSAGES_RECEIVED" "$messages_received"
        fi
    fi
}

# 检测EMQX主题详情
check_emqx_topics_detail() {
    # 获取主题总数
    local topic_count
    topic_count=$(emqx_exec emqx_ctl topics list 2>/dev/null | wc -l)

    if [ -n "$topic_count" ]; then
        output_result "EMQX_TOPICS_TOTAL" "$topic_count"
    fi

    # 获取TOP5主题
    local top5_topics
    top5_topics=$(emqx_exec emqx_ctl topics list 2>/dev/null | head -6 | tr '\n' '|' | sed 's/|$//')

    if [ -n "$top5_topics" ]; then
        output_result "EMQX_TOP5_TOPICS" "$top5_topics"
    fi
}

# 检测EMQX路由详情
check_emqx_routes_detail() {
    # 获取路由总数
    local route_count
    route_count=$(emqx_exec emqx_ctl routes list 2>/dev/null | wc -l)

    if [ -n "$route_count" ]; then
        output_result "EMQX_ROUTES_TOTAL" "$route_count"
    fi
}

# 检测EMQX监听器详情
check_emqx_listeners_detail() {
    # 获取监听器列表
    local listeners
    listeners=$(emqx_exec emqx_ctl listeners list 2>/dev/null)

    if [ -n "$listeners" ]; then
        # 统计监听器数量
        local listener_count
        listener_count=$(echo "$listeners" | grep -c "running" || echo "0")

        if [ -n "$listener_count" ]; then
            output_result "EMQX_LISTENERS_COUNT" "$listener_count"
        fi

        # 提取监听端口信息
        local listener_ports
        listener_ports=$(echo "$listeners" | grep "running" | awk '{print $4}' | tr '\n' ',' | sed 's/,$//')

        if [ -n "$listener_ports" ]; then
            output_result "EMQX_LISTENER_PORTS" "$listener_ports"
        fi
    fi
}

# 检测EMQX集群状态
check_emqx_cluster_detail() {
    # 获取集群状态
    local cluster_status
    cluster_status=$(emqx_exec emqx_ctl cluster status 2>/dev/null)

    if [ -n "$cluster_status" ]; then
        # 检查是否为集群模式
        local is_running_cluster
        is_running_cluster=$(echo "$cluster_status" | grep -c "is running" || echo "0")
        local is_stopped_cluster
        is_stopped_cluster=$(echo "$cluster_status" | grep -c "is stopped" || echo "0")
        local total_nodes=$((is_running_cluster + is_stopped_cluster))

        if [ "$total_nodes" -gt 1 ]; then
            output_result "EMQX_CLUSTER_MODE" "是"
            output_result "EMQX_CLUSTER_NODES" "$total_nodes"
        else
            output_result "EMQX_CLUSTER_MODE" "否（单节点）"
            output_result "EMQX_CLUSTER_NODES" "1"
        fi
    else
        output_result "EMQX_CLUSTER_MODE" "否（单节点）"
        output_result "EMQX_CLUSTER_NODES" "1"
    fi
}

# 检测EMQX连接限制
check_emqx_connection_limits() {
    # 获取最大连接数配置
    local max_connections
    max_connections=$(emqx_exec emqx_ctl listeners list 2>/dev/null | grep "max_connections" | awk '{print $NF}' | head -1)

    if [ -n "$max_connections" ]; then
        output_result "EMQX_MAX_CONNECTIONS" "$max_connections"
    fi

    # 获取当前连接数
    local current_connections
    current_connections=$(emqx_exec emqx_ctl clients list 2>/dev/null | wc -l)

    if [ -n "$current_connections" ] && [ -n "$max_connections" ] && [ "$max_connections" != "infinity" ]; then
        local conn_percent
        conn_percent=$(awk "BEGIN {printf \"%.1f\", ($current_connections * 100) / $max_connections}")
        output_result "EMQX_CONN_USAGE" "${conn_percent}%"

        # 判断连接使用率
        local level="正常"
        if (( $(awk "BEGIN {print ($conn_percent > 90)}") )); then
            level="严重"
        elif (( $(awk "BEGIN {print ($conn_percent > 80)}") )); then
            level="警告"
        fi

        output_result "EMQX_CONN_LEVEL" "$level"
    fi
}

# 检测EMQX内存使用
check_emqx_memory() {
    # 获取EMQX进程内存使用
    local emqx_pid
    emqx_pid=$(docker exec "$EMQX_CONTAINER" ps aux 2>/dev/null | grep "beam.smp" | grep -v grep | awk '{print $2}' | head -1)

    if [ -n "$emqx_pid" ]; then
        local mem_usage
        mem_usage=$(docker exec "$EMQX_CONTAINER" ps -p "$emqx_pid" -o %mem --no-headers 2>/dev/null | tr -d ' ')

        if [ -n "$mem_usage" ]; then
            output_result "EMQX_MEMORY_USAGE" "${mem_usage}%"
        fi
    fi
}

# 检测EMQX会话详情
check_emqx_sessions_detail() {
    # 获取会话总数
    local session_count
    session_count=$(emqx_exec emqx_ctl sessions list 2>/dev/null | wc -l)

    if [ -n "$session_count" ]; then
        output_result "EMQX_SESSIONS_TOTAL" "$session_count"
    fi

    # 统计会话状态
    local sessions_active
    sessions_active=$(emqx_exec emqx_ctl sessions list 2>/dev/null | grep -c "active" || echo "0")

    if [ -n "$sessions_active" ]; then
        output_result "EMQX_SESSIONS_ACTIVE" "$sessions_active"
        local sessions_inactive=$((session_count - sessions_active))
        output_result "EMQX_SESSIONS_INACTIVE" "$sessions_inactive"
    fi
}

# 检测EMQX插件状态
check_emqx_plugins() {
    # 获取已加载的插件列表
    local plugins
    plugins=$(emqx_exec emqx_ctl plugins list 2>/dev/null | grep "loaded" | awk '{print $1}' | tr '\n' ',' | sed 's/,$//')

    if [ -n "$plugins" ]; then
        output_result "EMQX_PLUGINS_LOADED" "$plugins"
    fi

    # 统计插件数量
    local plugin_count
    plugin_count=$(emqx_exec emqx_ctl plugins list 2>/dev/null | grep -c "loaded" || echo "0")

    if [ -n "$plugin_count" ]; then
        output_result "EMQX_PLUGINS_COUNT" "$plugin_count"
    fi
}

# 检测EMQX规则引擎状态
check_emqx_rules() {
    # 获取规则数量
    local rules_count
    rules_count=$(emqx_exec emqx_ctl rules list 2>/dev/null | wc -l)

    if [ -n "$rules_count" ] && [ "$rules_count" -gt 0 ]; then
        output_result "EMQX_RULES_COUNT" "$rules_count"
    else
        output_result "EMQX_RULES_COUNT" "未启用"
    fi
}

# 检测EMQX告警状态
check_emqx_alarms() {
    # 获取告警信息
    local alarms
    alarms=$(emqx_exec emqx_ctl alarms list 2>/dev/null)

    if [ -n "$alarms" ]; then
        # 统计告警数量
        local alarm_count
        alarm_count=$(echo "$alarms" | wc -l)

        if [ "$alarm_count" -gt 0 ]; then
            output_result "EMQX_ALARMS_COUNT" "$alarm_count"
            output_result "EMQX_ALARMS_LEVEL" "警告"

            # 获取告警详情
            local alarm_detail
            alarm_detail=$(echo "$alarms" | head -5 | tr '\n' '|' | sed 's/|$//')
            output_result "EMQX_ALARMS_DETAIL" "$alarm_detail"
        else
            output_result "EMQX_ALARMS_COUNT" "0"
            output_result "EMQX_ALARMS_LEVEL" "正常"
        fi
    else
        output_result "EMQX_ALARMS_COUNT" "0"
        output_result "EMQX_ALARMS_LEVEL" "正常"
    fi
}

# 检测EMQX性能指标
check_emqx_performance() {
    # 获取各种性能指标
    local metrics
    metrics=$(emqx_exec emqx_ctl metrics 2>/dev/null)

    if [ -n "$metrics" ]; then
        # 提取关键性能指标
        local conn_pkt recv_pkt send_pkt
        conn_pkt=$(echo "$metrics" | grep "packets.connect" | awk '{print $2}' || echo "0")
        recv_pkt=$(echo "$metrics" | grep "packets.received" | awk '{print $2}' || echo "0")
        send_pkt=$(echo "$metrics" | grep "packets.sent" | awk '{print $2}' || echo "0")

        if [ -n "$conn_pkt" ]; then
            output_result "EMQX_PACKETS_CONN" "$conn_pkt"
        fi

        if [ -n "$recv_pkt" ]; then
            output_result "EMQX_PACKETS_RECV" "$recv_pkt"
        fi

        if [ -n "$send_pkt" ]; then
            output_result "EMQX_PACKETS_SENT" "$send_pkt"
        fi
    fi
}

# 检测EMQX Dashboard状态
check_emqx_dashboard() {
    local dashboard_status="未启用"
    local dashboard_level="正常"
    local dashboard_url=""
    local dashboard_port="18083"

    # 直接尝试访问Dashboard
    local http_response
    http_response=$(emqx_exec curl -s -e "curl -s -m 3 --max-time 3 http://localhost:$dashboard_port" 2>/dev/null | head -c 1000)

    if [ -n "$http_response" ]; then
        if echo "$http_response" | grep -qiE "emqx|dashboard|login|mqtt"; then
            dashboard_status="可访问"
            dashboard_level="正常"
            dashboard_url="http://localhost:$dashboard_port"

            local dashboard_version
            dashboard_version=$(echo "$http_response" | grep -oE "v[0-9.]+" | head -1)
            if [ -n "$dashboard_version" ]; then
                output_result "EMQX_DASHBOARD_VERSION" "$dashboard_version"
            fi
        else
            dashboard_status="响应异常"
            dashboard_level="警告"
        fi
    fi

    # 检查其他可能的Dashboard端口
    if [ "$dashboard_status" = "未启用" ]; then
        local alt_ports=("8081" "8083" "8883")
        for alt_port in "${alt_ports[@]}"; do
            local alt_response
            alt_response=$(emqx_exec curl -s -m 2 --max-time 2 "http://localhost:$alt_port" 2>/dev/null | head -c 500)

            if [ -n "$alt_response" ]; then
                if echo "$alt_response" | grep -qiE "emqx|dashboard|login|mqtt"; then
                    dashboard_status="可访问（端口$alt_port）"
                    dashboard_level="正常"
                    dashboard_url="http://localhost:$alt_port"
                    break
                fi
            fi
        done
    fi

    output_result "EMQX_DASHBOARD_STATUS" "$dashboard_status"
    output_result "EMQX_DASHBOARD_LEVEL" "$dashboard_level"

    if [ -n "$dashboard_url" ]; then
        output_result "EMQX_DASHBOARD_URL" "$dashboard_url"
    fi
}

# ==================== 主检测流程 ====================
main() {
    log_info "开始EMQX深度检测..."

    # 在检测前先找到实际的容器名
    if command -v docker &> /dev/null; then
        # 尝试精确匹配
        local actual_container=$(docker ps --format "{{.Names}}" | grep -x "${EMQX_CONTAINER}" | head -1)

        # 如果精确匹配失败，尝试模糊匹配
        if [ -z "$actual_container" ]; then
            actual_container=$(docker ps --format "{{.Names}}" | grep -i "emqx" | head -1)
        fi

        # 更新EMQX_CONTAINER为实际找到的容器名
        if [ -n "$actual_container" ]; then
            EMQX_CONTAINER="$actual_container"
        fi
    fi

    if [ -z "$EMQX_CONTAINER" ]; then
        log_warn "EMQX容器未运行"
        output_result "EMQX_CONTAINER_STATUS" "未运行"
        return 1
    fi

    output_result "EMQX_CONTAINER" "$EMQX_CONTAINER"
    output_result "EMQX_CONTAINER_STATUS" "运行中"

    # 执行各项深度检测（添加错误处理，确保部分失败不影响其他检测）
    check_emqx_status_detail 2>/dev/null || true
    check_emqx_clients_detail 2>/dev/null || true
    check_emqx_subscriptions_detail 2>/dev/null || true
    check_emqx_messages_stats 2>/dev/null || true
    check_emqx_topics_detail 2>/dev/null || true
    check_emqx_routes_detail 2>/dev/null || true
    check_emqx_listeners_detail 2>/dev/null || true
    check_emqx_cluster_detail 2>/dev/null || true
    check_emqx_connection_limits 2>/dev/null || true
    check_emqx_memory 2>/dev/null || true
    check_emqx_sessions_detail 2>/dev/null || true
    check_emqx_plugins 2>/dev/null || true
    check_emqx_rules 2>/dev/null || true
    check_emqx_alarms 2>/dev/null || true
    check_emqx_performance 2>/dev/null || true
    check_emqx_dashboard 2>/dev/null || true

    log_info "EMQX深度检测完成"
}

# 执行主函数
main
