#!/bin/sh

###############################################################################
#
# router - management script to handle route table
# 
# Primary purpose is to :
# 1) add routes from the routes file to the route table.  This is call by 
#       by network startup script. 
# 2) update the default route to the route table, as called by the API.
#
#  route table = /etc/sysconfig/network/routes
#
# Copyright (c) 2006, all rights reserved
# License- GPL
# Author-  Mike Goins
# Company- Adtec Digital, Inc.
# Date-    2006-05-11
# Last Modified- 2006-10-11 by GMC
# Changed default MASK to 0.0.0.0 to fix gateway init issue
################################################################################

shopt -s -o nounset

declare -rx ROUTECONF="/etc/sysconfig/network/routes"
declare -x GW=`route -n | grep "^0.0.0.0" | head -1 | cut -c 17-32`  # gets the default route
GW=`expr "$GW" : '[[:space:]]*\(.*\)[[:space:]]*$'`        # strip whitespace
if [ -z "$GW" ]; then GW="0.0.0.0"; fi                       # if no default, then use 0.0.0.0
 
declare NUM

startup () {
    echo "Adding Startup routes: "
    # TODO  add netmask handling?
    while read DEST GWAY MASK IFACE ; do
        test "$DEST" = "-" && DEST=""
        test "$GWAY" = "-" && GWAY=""
        test "$MASK" = "-" && MASK="0.0.0.0"
        test "$IFACE" = "-" && IFACE=""
        echo "Gateway $GWAY for $DEST"
        route add -net $DEST netmask $MASK gw $GWAY $IFACE &>/dev/null
    done < $ROUTECONF
    echo "Routes complete"
}

if [ $# -eq 0 ] ; then
    echo $GW                   # just echo the default GW
elif [ $# -eq 1 ]; then 
    if [ "$1" == "startup" ]; then
        startup
    else
        route del default gw $GW &>/dev/null
        route add default gw $1 &>/dev/null 
        if [ $? -ne 0 -a "$1" != "0.0.0.0" ] ; then   # did not add, restore the old GW
             route add default gw $GW &>/dev/null
             exit 2
        else 
             # make the persistent change
             vi -e -n -c "%s/\(^default \)[\.0-9]*\(.*$\)/\1${1}\2/g | w! | q" $ROUTECONF &>/dev/null
        fi
    fi
else
    exit 2
fi

exit 0
