#!/bin/bash

function usage() {
    echo "Use: $0 interface metric"
    exit 0
}

function echo_error(){
    local t_msg=$*
    local t_time=$(date +%Y/%m/%d-%H:%M:%S)
    echo -e "[${t_time}]\t | [ERROR] | ${t_msg}"
}

function echo_info(){
    local t_msg=$*
    local t_time=$(date +%Y/%m/%d-%H:%M:%S)
    echo -e "[${t_time}]\t | [info] | ${t_msg}"
}

if [ "$(id -u)" -ne 0 ]; then
    echo "Script must be run as root. Try 'sudo $0'" 
    exit 1
fi

if [ $# -eq 2 ];then
    INTERFACE=$1
    NEW_METRIC=$2
    ip route show | grep "dev $INTERFACE" | while read -r route; do
        echo "$route" | grep -q "metric ${NEW_METRIC}" && continue
        echo "modify: ${route}"
        if ! echo "$route" | grep -q "metric"; then
            new_route=$(echo "$route" | sed -E "s/$/ metric ${NEW_METRIC}/")
        else
            new_route=$(echo "$route" | sed -E "s/metric [0-9]+/metric ${NEW_METRIC}/")
        fi
        ip route del $route
        ip route add $new_route
    done
else
    usage
    exit 1
fi