#!/bin/bash

# 定义颜色
RED='\033[0;31m'
NC='\033[0m' # No Color

CONFIG_FILE="/etc/network/interfaces"

if [ ! -f "$CONFIG_FILE" ]; then
    echo "配置文件不存在: $CONFIG_FILE"
    exit 1
fi

# 1. 提取所有 bond 接口名称
bond_interfaces=$(grep -E "^iface\s+bond[0-9]+" "$CONFIG_FILE" | awk '{print $2}')

# 2. 遍历每一个 bond
for bond in $bond_interfaces; do
    # 提取 slaves (成员网卡)
    slaves_line=$(grep -A 10 "iface $bond" "$CONFIG_FILE" | grep "slaves" | head -n 1)
    slaves=$(echo "$slaves_line" | sed 's/slaves//g' | xargs)

    # 3. 遍历每一个 slave 网卡
    for slave in $slaves; do
        # 获取网卡状态信息
        link_info=$(ip link show "$slave" 2>/dev/null)
        
        # 检查是否包含 NO-CARRIER (物理层断开)
        is_no_carrier=$(echo "$link_info" | grep "NO-CARRIER")
        # 提取 state 状态
        state_status=$(echo "$link_info" | grep -o "state [A-Z]*" | awk '{print $2}')

        # 核心逻辑：只有在 检测到 NO-CARRIER 时才输出
        if [ -n "$is_no_carrier" ]; then
            echo -e "  [${RED}DOWN${NC}] $slave: 物理链路断开 (NO-CARRIER, state $state_status) -> 请检查网线!"
        fi
    done
done
