#!/bin/bash
################################################################################
# 磁盘资源检测模块
# 功能: 检测磁盘使用率、Inode使用率、磁盘IO状态、SMART健康状态等
# 作者: Claude Code
# 日期: 2026-05-09
################################################################################

# 获取脚本所在目录并加载依赖
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

# ==================== 检测函数 ====================

# 检测磁盘使用率
check_disk_usage() {
    local line_count=0

    # 从 df 命令获取磁盘信息
    while IFS= read -r line; do
        # 跳过标题行
        if [ "$line_count" -eq 0 ]; then
            line_count=1
            continue
        fi

        # 解析 df 输出
        # 格式: /dev/sda1       100G   50G   50G  50% /mount
        if echo "$line" | grep -qE "^(.+?)\s+(\d+\.?\d*[KMGTP]?)\s+(\d+\.?\d*[KMGTP]?)\s+(\d+\.?\d*[KMGTP]?)\s+(\d+)%\s+(.+)$"; then
            local filesystem=$(echo "$line" | awk '{print $1}')
            local used_percent=$(echo "$line" | awk '{print $5}' | sed 's/%//')
            local mountpoint=$(echo "$line" | awk '{print $6}')
            local used_size=$(echo "$line" | awk '{print $3}')
            local total_size=$(echo "$line" | awk '{print $2}')
            local avail_size=$(echo "$line" | awk '{print $4}')

            # 判断状态
            local status
            if [ "$used_percent" -ge $DISK_CRITICAL ]; then
                status="严重"
            elif [ "$used_percent" -ge $DISK_WARNING ]; then
                status="警告"
            else
                status="正常"
            fi

            # 输出结果（使用唯一的key）
            local key_name="DISK_${mountpoint}"
            # 替换路径中的 / 为 _ 以作为合法的变量名
            key_name=$(echo "$key_name" | tr '/' '_')
            output_result "${key_name}_USAGE" "${used_percent}%"
            output_result "${key_name}_USED" "$used_size"
            output_result "${key_name}_TOTAL" "$total_size"
            output_result "${key_name}_AVAILABLE" "$avail_size"
            output_result "${key_name}_STATUS" "$status"

            # 如果状态异常，输出错误信息
            if [ "$status" != "正常" ]; then
                echo "ERROR:磁盘使用率过高: ${mountpoint} (${used_percent}%)"
            fi
        fi
    done < <(df -h 2>/dev/null | tail -n +2)
}

# 检测Inode使用率
check_inode_usage() {
    local line_count=0

    # 从 df -i 命令获取Inode信息
    while IFS= read -r line; do
        # 跳过标题行
        if [ "$line_count" -eq 0 ]; then
            line_count=1
            continue
        fi

        # 解析 df -i 输出
        local used_percent=$(echo "$line" | awk '{print $5}' | sed 's/%//')
        local mountpoint=$(echo "$line" | awk '{print $6}')

        # 只报告使用率超过90%的
        if [ "$used_percent" -ge 90 ]; then
            local status
            if [ "$used_percent" -ge $DISK_CRITICAL ]; then
                status="严重"
            elif [ "$used_percent" -ge $DISK_WARNING ]; then
                status="警告"
            else
                status="正常"
            fi

            local key_name="INODE_${mountpoint}"
            key_name=$(echo "$key_name" | tr '/' '_')

            output_result "${key_name}_USAGE" "${used_percent}%"
            output_result "${key_name}_STATUS" "$status"

            if [ "$status" != "正常" ]; then
                echo "ERROR:Inode使用率过高: ${mountpoint} (${used_percent}%)"
            fi
        fi
    done < <(df -i 2>/dev/null | tail -n +2)
}

# 检测磁盘IO状态
check_disk_io() {
    if command -v iostat &> /dev/null; then
        # 执行 iostat 获取IO数据
        local io_output
        io_output=$(iostat -x 1 2 2>/dev/null | grep -v "^$" | tail -n +4)

        if [ -n "$io_output" ]; then
            output_result "DISK_IO_STATUS" "已获取"
        else
            output_result "DISK_IO_STATUS" "iostat不可用"
        fi
    else
        output_result "DISK_IO_STATUS" "未安装iostat"
    fi
}

# 检测磁盘SMART健康状态
check_disk_smart() {
    if command -v smartctl &> /dev/null; then
        # 获取主要磁盘设备
        local disk_device=""
        for dev in /dev/sda /dev/vda /dev/nvme0n1; do
            if [ -e "$dev" ]; then
                disk_device="$dev"
                break
            fi
        done

        if [ -n "$disk_device" ]; then
            local smart_output
            smart_output=$(smartctl -H "$disk_device" 2>/dev/null)

            if echo "$smart_output" | grep -q "PASSED" || echo "$smart_output" | grep -q "OK"; then
                output_result "DISK_SMART_STATUS" "正常"
            elif echo "$smart_output" | grep -q "FAILED"; then
                output_result "DISK_SMART_STATUS" "严重"
                echo "ERROR:磁盘SMART检测失败"
            else
                output_result "DISK_SMART_STATUS" "未知"
            fi
        else
            output_result "DISK_SMART_STATUS" "无可用设备"
        fi
    else
        output_result "DISK_SMART_STATUS" "未安装smartctl"
    fi
}

# 检测磁盘分区信息
check_disk_partitions() {
    local partitions
    partitions=$(lsblk -o NAME,SIZE,TYPE,MOUNTPOINT -n 2>/dev/null | grep -v "rom" | grep -v "loop")

    if [ -n "$partitions" ]; then
        output_result "DISK_PARTITIONS" "已获取"
    else
        output_result "DISK_PARTITIONS" "获取失败"
    fi
}

# 检测磁盘读写速度
check_disk_speed() {
    if command -v dd &> /dev/null; then
        # 创建测试文件
        local test_file="/tmp/.disk_speed_test_$$"

        # 写入测试 (100MB)
        local write_speed
        write_speed=$(dd if=/dev/zero of="$test_file" bs=1M count=100 2>&1 | grep -oP '\d+(\.\d+)? MB/s' | head -1)

        # 读取测试
        local read_speed
        read_speed=$(dd if="$test_file" of=/dev/null bs=1M 2>&1 | grep -oP '\d+(\.\d+)? MB/s' | head -1)

        # 清理测试文件
        rm -f "$test_file"

        if [ -n "$write_speed" ]; then
            output_result "DISK_WRITE_SPEED" "$write_speed"
        fi

        if [ -n "$read_speed" ]; then
            output_result "DISK_READ_SPEED" "$read_speed"
        fi
    else
        output_result "DISK_SPEED_TEST" "dd命令不可用"
    fi
}

# 检测磁盘延迟统计
check_disk_latency() {
    if [ -f /proc/diskstats ]; then
        # 获取前几个磁盘的延迟信息
        local disk_latency
        disk_latency=$(head -5 /proc/diskstats 2>/dev/null | awk '{print $3":"$4":"$7":"$8}' | tr '\n' ',' | sed 's/,$//')
        if [ -n "$disk_latency" ]; then
            output_result "DISK_LATENCY" "$disk_latency"
        fi
    fi
}

# 检查网络文件系统挂载
check_nfs_mounts() {
    local nfs_mounts
    nfs_mounts=$(mount | grep -E "(nfs|cifs|smbfs|fuse.sshfs)" 2>/dev/null | awk '{print $1":"$3}' | tr '\n' ',' | sed 's/,$//')

    if [ -n "$nfs_mounts" ]; then
        output_result "REMOTE_MOUNTS" "$nfs_mounts"
        output_result "REMOTE_MOUNTS_COUNT" "$(echo "$nfs_mounts" | tr ',' '\n' | wc -l)"
    else
        output_result "REMOTE_MOUNTS_COUNT" "0"
    fi
}

# 检测RAID状态
check_raid_status() {
    if [ -f /proc/mdstat ]; then
        local mdstat
        mdstat=$(cat /proc/mdstat 2>/dev/null)
        if [ -n "$mdstat" ]; then
            # 检查是否有RAID设备
            if echo "$mdstat" | grep -q "md"; then
                local raid_devices
                raid_devices=$(echo "$mdstat" | grep -oE "md[0-9]+" | tr '\n' ',' | sed 's/,$//')
                output_result "RAID_DEVICES" "$raid_devices"

                # 检查RAID状态
                if echo "$mdstat" | grep -q "\[UU+\]"; then
                    output_result "RAID_STATUS" "正常"
                elif echo "$mdstat" | grep -q "\[UU\]"; then
                    output_result "RAID_STATUS" "正常"
                else
                    output_result "RAID_STATUS" " degraded"
                fi
            else
                output_result "RAID_STATUS" "无RAID设备"
            fi
        else
            output_result "RAID_STATUS" "无法读取"
        fi
    else
        output_result "RAID_STATUS" "无/proc/mdstat"
    fi
}

# 检测LVM状态
check_lvm_status() {
    if command -v lvs &> /dev/null; then
        local lvm_info
        lvm_info=$(lvs --noheadings --separator ',' -o lv_name,lv_size,lv_attr 2>/dev/null)
        if [ -n "$lvm_info" ]; then
            output_result "LVM_VOLUMES" "$lvm_info"
        fi
    else
        output_result "LVM_STATUS" "未安装lvs"
    fi
}

# 检测磁盘调度算法
check_disk_scheduler() {
    local scheduler=""
    # 检查第一个块设备的调度器
    for disk in /sys/block/*; do
        if [ -d "$disk/queue/scheduler" ]; then
            local dev_name=$(basename "$disk")
            scheduler=$(cat "$disk/queue/scheduler" 2>/dev/null | grep -oP '\[[^\]]+\]' | tr -d '[]')
            output_result "DISK_SCHEDULER_${dev_name}" "$scheduler"
            break
        fi
    done
}

# ==================== 主检测流程 ====================
main() {
    log_info "开始磁盘资源检测..."

    # 执行各项检测
    check_disk_usage
    check_inode_usage
    check_disk_io
    check_disk_smart
    check_disk_partitions
    check_disk_latency
    check_nfs_mounts
    check_raid_status
    check_lvm_status
    check_disk_scheduler
    # check_disk_speed  # 可选，比较耗时

    log_info "磁盘资源检测完成"
}

# 执行主函数
main
