#!/bin/bash
set -euo pipefail
MAIN_TABLE="main"
RT_TABLES_FILE="/etc/iproute2/rt_tables"

check_root() {
    if [ $EUID -ne 0 ]; then
        echo "错误：操作路由表需要root权限，请使用sudo运行脚本！"
        exit 1
    fi
}
get_custom_tables() {
    grep -vE '^#|^$' "${RT_TABLES_FILE}" | awk '{print $1}' | \
    grep -E '^[0-9]+$' | grep -v "^${MAIN_TABLE}$" | sort -n | uniq | tr '\n' ' ' | sed 's/ $//'
}

sync_ipv4_routes() {
    local custom_tables="$1"
    local ipv4_routes
    ipv4_routes=$(ip -4 route show table "${MAIN_TABLE}" proto kernel scope link)
    local ipv4_count=$(echo "${ipv4_routes}" | grep -c .)

    if [ ${ipv4_count} -gt 0 ]; then
        echo "${ipv4_routes}" | while read -r route; do
            [ -z "${route}" ] && continue
            for table in ${custom_tables}; do
                ip -4 route replace ${route} table ${table} >/dev/null 2>&1
            done
            #echo "${route} -->  ${custom_tables}"
        done
        echo "IPv4同步完成,共${ipv4_count}条"
    else
        echo "IPv4无直连路由"
    fi
}

sync_ipv6_routes() {

    local custom_tables="$1"
    local ipv6_routes
    ipv6_routes=$(ip -6 route show table "${MAIN_TABLE}" proto kernel metric 256)
    local ipv6_count=$(echo "${ipv6_routes}" | grep -c .)

    if [ ${ipv6_count} -gt 0 ]; then
        echo "${ipv6_routes}" | while read -r route; do
            [ -z "${route}" ] && continue
            for table in ${custom_tables}; do
                ip -6 route replace ${route} table ${table} >/dev/null 2>&1
            done
            #echo "${route} -->  ${custom_tables}"
        done
        echo "IPv6同步完成,共${ipv6_count}条"
    else
        echo "IPv6无直连路由可同步"
    fi
}

main() {
    check_root
    local CUSTOM_TABLES=$(get_custom_tables)
    if [ -z "${CUSTOM_TABLES}" ]; then
        echo "提示：${RT_TABLES_FILE}中无自定义路由表（已排除254主表），退出执行"
        exit 0
    fi
    echo "获取到路由表：${CUSTOM_TABLES}"
    sync_ipv4_routes "${CUSTOM_TABLES}"
    sync_ipv6_routes "${CUSTOM_TABLES}"

    echo "所有路由同步完成！"
}

main