#!/bin/bash
# 56_fastdfs_check.sh - FastDFS 功能验证检测
# 只检测服务状态，不执行实际上传下载操作（避免超时）

output_result() {
    local key="$1"
    local value="$2"
    echo "${key}: ${value}"
}

# 从 config.sh 读取配置
CONTAINERS["tracker"]="tracker|utracker"
CONTAINERS["storage"]="storage|ustorage"

# 自动检测 FastDFS 容器
detect_containers() {
    local tracker_container=""
    local storage_container=""

    # Tracker 容器
    tracker_container=$(docker ps --format "{{.Names}}" | grep -iE "${CONTAINERS[tracker]}" | head -1)
    if [[ -z "$tracker_container" ]]; then
        tracker_container=$(docker ps -a --format "{{.Names}}" | grep -iE "${CONTAINERS[tracker]}" | head -1)
    fi

    # Storage 容器（可能与 Tracker 是同一个）
    storage_container=$(docker ps --format "{{.Names}}" | grep -iE "${CONTAINERS[storage]}" | head -1)
    if [[ -z "$storage_container" ]]; then
        storage_container=$(docker ps -a --format "{{.Names}}" | grep -iE "${CONTAINERS[storage]}" | head -1)
    fi

    echo "$tracker_container|$storage_container"
}

# 主检测逻辑
main() {
    local containers_raw
    containers_raw=$(detect_containers)
    local tracker_container="${containers_raw%%|*}"
    local storage_container="${containers_raw##*|}"

    # 1. 容器状态
    if [[ -n "$tracker_container" ]]; then
        local tracker_status
        tracker_status=$(docker inspect -f '{{.State.Status}}' "$tracker_container" 2>/dev/null || echo "unknown")
        output_result "FDFS_CONTAINER_TRACKER" "$tracker_container ($tracker_status)"
    else
        output_result "FDFS_CONTAINER_TRACKER" "未检测到"
    fi

    if [[ -n "$storage_container" ]] && [[ "$storage_container" != "$tracker_container" ]]; then
        local storage_status
        storage_status=$(docker inspect -f '{{.State.Status}}' "$storage_container" 2>/dev/null || echo "unknown")
        output_result "FDFS_CONTAINER_STORAGE" "$storage_container ($storage_status)"
    else
        output_result "FDFS_CONTAINER_STORAGE" "与Tracker同容器"
    fi

    # 2. 端口检测（使用宿主机 ss，不依赖容器内命令）
    local ports_ok=0
    local ports_total=3
    local ports_detail=""

    # 22122 - Tracker
    if ss -tln 2>/dev/null | grep -q ":22122 "; then
        ((ports_ok++))
        ports_detail+="22122(Tracker):监听 "
    else
        ports_detail+="22122(Tracker):未监听 "
    fi

    # 23000 - Storage
    if ss -tln 2>/dev/null | grep -q ":23000 "; then
        ((ports_ok++))
        ports_detail+="23000(Storage):监听 "
    else
        ports_detail+="23000(Storage):未监听 "
    fi

    # 8888 - Nginx HTTP
    if ss -tln 2>/dev/null | grep -q ":8888 "; then
        ((ports_ok++))
        ports_detail+="8888(HTTP):监听"
    else
        ports_detail+="8888(HTTP):未监听"
    fi

    output_result "FDFS_PORTS_OK" "$ports_ok"
    output_result "FDFS_PORTS_TOTAL" "$ports_total"
    output_result "FDFS_PORTS_DETAIL" "$ports_detail"

    if [[ $ports_ok -eq $ports_total ]]; then
        output_result "FDFS_PORTS_LEVEL" "正常"
    elif [[ $ports_ok -gt 0 ]]; then
        output_result "FDFS_PORTS_LEVEL" "警告"
    else
        output_result "FDFS_PORTS_LEVEL" "严重"
    fi

    # 3. 进程检测（在 Tracker 容器内检查）
    local target_container="${tracker_container:-$storage_container}"

    if [[ -n "$target_container" ]]; then
        local process_status=""

        # 检查 fdfs_trackerd 进程
        if docker exec "$target_container" ps aux 2>/dev/null | grep -q "[f]dfs_trackerd"; then
            process_status+="trackerd:运行 "
        else
            process_status+="trackerd:未运行 "
        fi

        # 检查 fdfs_storaged 进程
        if docker exec "$target_container" ps aux 2>/dev/null | grep -q "[f]dfs_storaged"; then
            process_status+="storaged:运行"
        else
            process_status+="storaged:未运行"
        fi

        output_result "FDFS_PROCESS_STATUS" "$process_status"

        if echo "$process_status" | grep -q "未运行"; then
            output_result "FDFS_PROCESS_LEVEL" "警告"
        else
            output_result "FDFS_PROCESS_LEVEL" "正常"
        fi

        # 4. 配置文件检测
        local client_conf="/etc/fdfs/client.conf"
        if docker exec "$target_container" test -f "$client_conf" 2>/dev/null; then
            output_result "FDFS_CONFIG_EXISTS" "yes"

            local tracker_server
            tracker_server=$(docker exec "$target_container" grep "^tracker_server" "$client_conf" 2>/dev/null | head -1 | awk -F= '{print $2}')
            output_result "FDFS_TRACKER_SERVER" "${tracker_server:-未配置}"

            output_result "FDFS_CONFIG_LEVEL" "正常"
        else
            output_result "FDFS_CONFIG_EXISTS" "no"
            output_result "FDFS_TRACKER_SERVER" "配置文件不存在"
            output_result "FDFS_CONFIG_LEVEL" "警告"
        fi
    else
        output_result "FDFS_PROCESS_STATUS" "无容器"
        output_result "FDFS_PROCESS_LEVEL" "严重"
        output_result "FDFS_CONFIG_EXISTS" "no"
        output_result "FDFS_TRACKER_SERVER" "无容器"
        output_result "FDFS_CONFIG_LEVEL" "严重"
    fi

    # 5. HTTP 访问测试（简单探测，有超时）
    if ss -tln 2>/dev/null | grep -q ":8888 "; then
        local http_code
        http_code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 3 --max-time 5 "http://127.0.0.1:8888/" 2>/dev/null || echo "000")

        if [[ "$http_code" =~ ^(200|403|404)$ ]]; then
            # 200=正常, 403/404=服务在运行只是路径问题
            output_result "FDFS_HTTP_STATUS" "服务响应"
            output_result "FDFS_HTTP_CODE" "$http_code"
            output_result "FDFS_HTTP_LEVEL" "正常"
        elif [[ "$http_code" == "000" ]]; then
            output_result "FDFS_HTTP_STATUS" "连接失败"
            output_result "FDFS_HTTP_CODE" "timeout"
            output_result "FDFS_HTTP_LEVEL" "警告"
        else
            output_result "FDFS_HTTP_STATUS" "异常响应"
            output_result "FDFS_HTTP_CODE" "$http_code"
            output_result "FDFS_HTTP_LEVEL" "警告"
        fi
    else
        output_result "FDFS_HTTP_STATUS" "端口未监听"
        output_result "FDFS_HTTP_CODE" "N/A"
        output_result "FDFS_HTTP_LEVEL" "严重"
    fi

    # 6. 总体状态
    if [[ $ports_ok -eq $ports_total ]] && [[ -n "$target_container" ]]; then
        output_result "FDFS_STATUS" "正常"
        output_result "FDFS_STATUS_LEVEL" "正常"
    elif [[ $ports_ok -gt 0 ]]; then
        output_result "FDFS_STATUS" "部分异常"
        output_result "FDFS_STATUS_LEVEL" "警告"
    else
        output_result "FDFS_STATUS" "服务异常"
        output_result "FDFS_STATUS_LEVEL" "严重"
    fi
}

main
