#!/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_container() {
    local container_status="未运行"
    local level="严重"
    local matched_container=""

    if command -v docker &> /dev/null; then
        # 尝试精确匹配
        matched_container=$(docker ps --format "{{.Names}}" | grep -x "${EMQX_CONTAINER}" | head -1)

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

        if [ -n "$matched_container" ]; then
            container_status="运行中 (${matched_container})"
            level="正常"
            # 更新全局变量
            eval "EMQX_CONTAINER='${matched_container}'"
        else
            # 检查容器是否存在但未运行
            matched_container=$(docker ps -a --format "{{.Names}}" | grep -i "${EMQX_CONTAINER}" | head -1)
            if [ -n "$matched_container" ]; then
                container_status="已停止 (${matched_container})"
                level="警告"
            fi
        fi
    fi

    output_result "EMQX_CONTAINER_STATUS" "$container_status"
    output_result "EMQX_CONTAINER_LEVEL" "$level"

    if [ "$level" != "正常" ]; then
        return 1
    fi

    return 0
}

# 检测EMQX版本
check_emqx_version() {
    local version=""

    version=$(emqx_exec emqx_ctl broker 2>/dev/null | grep "version" | cut -d: -f2 | tr -d ' ')

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

# 检测EMQX状态
check_emqx_status() {
    local status="未知"

    if emqx_exec emqx_ctl status 2>/dev/null | grep -q "is running\|Node"; then
        status="运行中"
        output_result "EMQX_STATUS" "$status"
        output_result "EMQX_STATUS_LEVEL" "正常"
    else
        status="异常"
        output_result "EMQX_STATUS" "$status"
        output_result "EMQX_STATUS_LEVEL" "严重"
    fi
}

# 检测EMQX客户端连接
check_emqx_clients() {
    local client_count=0

    client_count=$(emqx_exec emqx_ctl clients list 2>/dev/null | wc -l)

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

# 检测EMQX会话数
check_emqx_sessions() {
    local session_count=0

    session_count=$(emqx_exec emqx_ctl sessions list 2>/dev/null | wc -l)

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

# 检测EMQX订阅数
check_emqx_subscriptions() {
    local sub_count=0

    sub_count=$(emqx_exec emqx_ctl subscriptions list 2>/dev/null | wc -l)

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

# 检测EMQX主题数
check_emqx_topics() {
    local topic_count=0

    topic_count=$(emqx_exec emqx_ctl topics list 2>/dev/null | wc -l)

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

# 检测EMQX路由数
check_emqx_routes() {
    local route_count=0

    route_count=$(emqx_exec emqx_ctl routes list 2>/dev/null | wc -l)

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

# 检测EMQX监听端口
check_emqx_listeners() {
    local listeners=""

    listeners=$(emqx_exec emqx_ctl listeners list 2>/dev/null | grep "running" | wc -l)

    if [ -n "$listeners" ]; then
        output_result "EMQX_LISTENERS" "$listeners"
    fi
}

# 检测EMQX集群状态
check_emqx_cluster() {
    local cluster_status="未知"

    if emqx_exec emqx_ctl cluster status 2>/dev/null | grep -q "is running\|Cluster"; then
        cluster_status="正常"
    else
        cluster_status="未配置"
    fi

    output_result "EMQX_CLUSTER" "$cluster_status"
}

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

    # 检查容器状态
    if ! check_emqx_container; then
        log_warn "EMQX容器未运行，跳过其他检测"
        return
    fi

    # 执行各项检测
    check_emqx_version
    check_emqx_status
    check_emqx_clients
    check_emqx_sessions
    check_emqx_subscriptions
    check_emqx_topics
    check_emqx_routes
    check_emqx_listeners
    check_emqx_cluster

    log_info "EMQX基础检测完成"
}

# 执行主函数
main
