#!/bin/bash
#
# rrqnet helper script for establishing a rule based route table for a
# given interface with given IP with default route to given gateway IP
# on the interface link.
# $1 = interface
# $2 = interface IP
# $3 = gateway IP
#
# This will retry every second until the setup is successful. Should
# be spawned in a conf file, eg:
# /etc/rrqnet/set-source-route.sh $TAP $IP $GW > /dev/null 2>&1 &
#

TAP=$1
IP=$2
GW=$3
: ${TIX:=200}

function set-source-route() {
    grep -q "$TIX $TAP" /etc/iproute2/rt_tables || \
	echo "$TIX $TAP" >> /etc/iproute2/rt_tables
    if [ -z "$(ip rule list from ${IP%/*})" ] ; then
	ip rule add from ${IP%/*} lookup $TAP || return 1
    fi
    if [ -z "$(ip route show table $TAP | grep ^$GW)" ] ; then
	ip route add $GW dev $TAP scope link src ${IP%/*} table $TAP || \
	    return 1
    fi
    if [ -z "$(ip route show table $TAP | grep default)" ] ; then
	ip route add default via $GW dev $TAP table $TAP || return 1
    fi
    ip route show table $TAP
}

set-source-route && exit 0
sleep 1
exec $0 $*
