#!/bin/bash

# 获取当前的 IP 地址信息
echo "Current IP addresses with peers:"
ip_add_output=$(ip add | grep inet | grep peer)
echo "$ip_add_output"

# 获取当前的 IP 规则
echo "Current IP rules:"
ip_rule_output=$(ip rule show)
echo "$ip_rule_output"

# 查找并对比 IP 地址和规则
echo "Checking and updating IP rules if necessary:"
echo "$ip_add_output" | while read -r line ; do
    from=$(echo $line |  cut -d ' ' -f 2)
    dev=$(echo $line |  cut -d ' ' -f 7)
    table=$(echo $dev)

    # 查找对应的规则
    rule_line=$(echo "$ip_rule_output" | grep "lookup $table")
    if [ -n "$rule_line" ]; then
        rule_from=$(echo $rule_line |  cut -d ' ' -f 3)
        if [ "$from" != "$rule_from" ]; then
            # 删除已有的规则
            echo "Deleting inconsistent rule: ip rule del from $rule_from lookup $table"
            ip rule del lookup $table
            ip rule del lookup $table
            ip rule del lookup $table
            ip rule del lookup $table
            # 添加新的规则
            echo "Adding new route and rule: ip route add 0.0.0.0/0 dev $dev table $table"
            ip route add 0/0 dev $dev table $table
            echo "Adding new rule: ip rule add from $from table $table pref 200"
            ip rule add from $from table $table pref 200
        else
            echo "Rule for $table is consistent, skipping."
        fi
    else
        # 如果没有找到对应的规则，添加新的规则
        echo "No existing rule found for $table, adding new route and rule."
        echo "Adding new route: ip route add 0/0 dev $dev table $table"
        ip route add 0/0 dev $dev table $table
        echo "Adding new rule: ip rule add from $from table $table pref 200"
        ip rule add from $from table $table pref 200
    fi
done

# 显示更新后的 IP 规则
echo "Updated IP rules:"
ip rule show