#!/bin/sh

# /etc/network/interfaces example call:
# post-up /etc/network/dhcp-metric.sh eth0 100

set_route_metric() {
    local INTERFACE="$1"
    local METRIC="$2"

    local ROUTER=$(ip route | grep default | grep "$INTERFACE" | awk '{print $3}')

#    echo "ip route del default dev $INTERFACE"
#    ip route del default dev "$INTERFACE"

#    echo "ip route add default via $ROUTER dev $INTERFACE metric $METRIC"
#    ip route add default via "$ROUTER" dev "$INTERFACE" metric "$METRIC"

    local NETWORK=$(ip route | grep "$INTERFACE scope" | awk '!/^169/{print $1}')
    local SOURCE=$(ip route | grep "$INTERFACE scope" | awk '!/^169/{print $7}')

    echo "ip route del $NETWORK dev $INTERFACE"
    ip route del "$NETWORK" dev "$INTERFACE"

    echo "ip route add $NETWORK dev $INTERFACE scope link src $SOURCE metric $METRIC"
    ip route add "$NETWORK" dev "$INTERFACE" scope link src "$SOURCE" metric "$METRIC"
}

set_route_metric $1 $2
