#!/bin/sh
#
# Robin * Slomkowski <rslomkow@rslomkow.org>
# Sun Jun  4 21:35:29 PDT 2000
#
# This file should be in /etc/init.d/static_route
# This should follow /etc/init.d/networking
# So by default I sould put this at S36static_route
#
# Default Values
#

CONFIG_FILE=/etc/network/route.conf
ACTION=start
PATH=/bin:/usr/bin:/sbin:/usr/sbin

#
# Functions
#

function usage {
  echo "$0: [start|stop] [-f configfile]"
}

function mk_route_arg {
# pipe a configfile line into this and it will give you
# the arguments to route
# warning that thing in [] is space " " tab "	" may not show up if you
# cut and paste
  sed -e 's/^[ 	]//;
    s/[ 	][ 	]*/__SEPERATOR__/g;
    s/^/-net /;s/__SEPERATOR__/ gw /;
    s/__SEPERATOR__/ netmask /;
    s/__SEPERATOR__/ metric /;
    s/__SEPERATOR__/ dev /;
    s/[^ ][^ ]* -//g;
    s/ /__SEPERATOR__/g'
}

#
# MAIN
#

# Get arguments

# No arguments uses the default ACTION value
if [ ! -z "$*" ] ; then
  if [ "$1" == 'start' -o  "$1" == 'stop' ] ; then
    ACTION=$1
    shift
  else
    usage
    exit 254
  fi
fi

# accept and alternate config file
if [ "$1" == '-f' ] ; then
  shift
  if [ -r "$1" ] ; then 
    CONFIG_FILE=$1
    shift
  else
    echo "$0: Error cannot read $1"
    usage
    exit 253
  fi
fi

# Now Get Perform actions

case "$ACTION" in
  'start' )
    echo "adding static routes"
    for i in `egrep -v '(^#|^$)' $CONFIG_FILE | \
              mk_route_arg`
    do
      ARGS=`echo $i | sed 's/__SEPERATOR__/ /g;'`
      echo "route add $ARGS"
      `route add $ARGS`
    done
  ;;
  'stop' )
    echo "removing static routes"
    for i in `egrep -v '(^#|^$)' $CONFIG_FILE | \
              mk_route_arg`
    do
      ARGS=`echo $i | sed 's/__SEPERATOR__/ /g;'`
      echo "route delete $ARGS"
      `route delete $ARGS`
    done
  ;;
  *)
    echo "$0: This error should not occur"
    usage
    exit 252
  ;;
esac
