#!/bin/bash


function set_ip_route(){
    local nic=$1
    local addr=$2
    local gate=$3
    local mask=$4
    if [ -z "$nic" ] || [ -z "$addr" ] || [ -z "$gate" ] || [ -z "$mask" ]; then
        return
    fi
    # 不注册
    # if [ -z "$(cat /etc/iproute2/rt_tables | grep "${nic}" | grep -v '#')" ];then
    #     echo ${mask} ${nic} >> /etc/iproute2/rt_tables # 注册路由表
    #     sleep 2 # 给系统响应时间
    # fi
    echo `date "+%Y-%m-%d %H:%M:%S"` $nic $addr $gate $mask >> ${RECORD_LOG}

    # brctl delif br-lan $nic
    # ip route flush table $nic # 清空刷新路由表
    # ip route add default dev $nic table $nic # 添加默认路由
    # ip rule add from $addr table $nic pref 200 # 强制 此地址 走此 $nic路由表
    # ip rule add to $addr lookup $nic pref 200 # 让访问 此地址 的走 $nic路由表
    # ip route replace default dev $nic table $nic via $gate # 添加网关
    # ip route add default via $gate dev $nic metric $mask
    brctl delif br-lan $nic
    ip route flush table $mask # 清空刷新路由表
    ip route add default dev $nic table $mask # 添加默认路由
    ip rule add from $addr table $mask pref 200 # 强制 此地址 走此 $nic路由表
    ip rule add to $addr lookup $mask pref 200 # 让访问 此地址 的走 $nic路由表
    ip route replace default dev $nic table $mask via $gate # 添加网关
    ip route add default via $gate dev $nic metric $mask
}

function clean_route(){
    local id=$1
    ip ru | grep 200 | grep "lookup ${id}" | awk -F '\t' '{print $2}' | while read info; do
        ip rule delete ${info}
    done
}

function clean_all_route(){
    ip ru | grep 200 | awk -F '\t' '{print $2}' | while read info; do
        ip rule delete ${info}
    done
}


ARGS=`getopt -o :s:c:a --long set_route:,clean_route:,clean_all_route -n "$0" -- "$@"`
if [ $? != 0 ]; then
    echo "Terminating..."
    exit 1
fi

echo ARGS=[$ARGS]
#将规范化后的命令行参数分配至位置参数（$1,$2,...)
eval set -- "${ARGS}"
echo formatted parameters=[$@]


case "$1" in
    -s | --set_route)
        set_ip_route $2
        #echo "set_route $2"
        shift 2;
    ;;
    -c | --clean_route)
        # mask
        clean_route $2
        #echo "clean_route $2"
        shift 2;
    ;;
    -a | --clean_all_route)
        clean_all_route
        # echo "clean_all_route"
        shift 2;
    ;;
    --)
        shift;
    ;;
    ?)
        echo "未知参数"
    exit;
    ;;
esac

