#!/bin/bash
HOST=http://169.254.169.254
COUNT=0
for DEV in `/sbin/ifconfig | grep -i "d0:.d" | grep "eth[0-9]* " | awk '{print $1}'`;do
    TABLE=$((${DEV:3}+100))
    IP="`/sbin/ifconfig "$DEV" | grep "inet " | awk '{print $2}' | awk -F":" '{print $2}'`"
    NETWORK_MASK=`ip route | grep -w "$DEV  proto"|awk '{print substr($1,1,length($1))}'`
    NETWORK=`ip route | grep -w "$DEV  proto"|awk '{print substr($1,1,length($1)-3)}'`
    GATEWAY=${NETWORK%.*}.$(expr ${NETWORK##*.} + 1)
    if [ -z $IP ]||[ -z $GATEWAY ];then
        continue
    fi
    ip route flush table $TABLE
    ip route add default via $GATEWAY dev $DEV src $IP table $TABLE prio 50
    ip route add $NETWORK_MASK dev $DEV src $IP table $TABLE prio 50
    ip rule add from $IP table $TABLE
    COUNT=$(($COUNT+1))
done
 
if [ $COUNT -lt "2" ];then
    exit
fi
for DEV in `/sbin/ifconfig | grep -i " d0:.d" | grep "eth[0-9]* " | awk '{print $1}'`;do
    NETWORK=`ip route | grep -w "$DEV  proto"|awk '{print substr($1,1,length($1)-3)}'`
    GATEWAY=${NETWORK%.*}.$(expr ${NETWORK##*.} + 1)
    TABLE=$((${DEV:3}+100))
    HW=`/sbin/ifconfig "$DEV"|tr '[A-Z]' '[a-z]' | sed -n "/ d0:.d/s/.*hwaddr *//p" | sed -n 's/:/_/gp'`
    FILENAME="${HW:0:6}route.txt"
    FILEPATH="/tmp/$FILENAME"
    wget $HOST/latest/meta-data/"$FILENAME" -q -O "$FILEPATH"; UNREACHEABLE=$?
    while [ $UNREACHEABLE -ne "0" ]
        do wget $HOST/latest/meta-data/"$FILENAME" -q -O "$FILEPATH"; UNREACHEABLE=$?; sleep 5;
    done
    while read line;do
        if [ -z $line ];then
            continue
        fi
        route add -net $line gw $GATEWAY
   done < "$FILEPATH"
done