#!/bin/sh

echo "ALL 0.0.0.0 0 NO" > netobjects
GATEWAY=`netstat -nr | awk '{if ($1 == "0.0.0.0") print $2}'`
GATEWAYDEV=`netstat -nr | awk '{if ($1 == "0.0.0.0") print $8}'`

cat interfaces | while read interface; do
  IP=`ifconfig $interface | grep inet | cut -d : -f 2 | cut -d \  -f 1`
  #
  # Find the network route that attaches to this IP.
  #
  NETADDR=`netstat -nr | awk '{if ($2 == P) print $1}' P=$IP`
  #
  # Use ifconfig to find the mask ... it might not be in the route table.
  #
  MASK=`ifconfig $interface | grep Mask | sed 's/^.*Mask://g'`
  #
  # If the network address is null, the interface is not in the route table
  # (eg: lo), so use the object address instead.
  #
  if [ -z "$NETADDR" ]; then
    NETADDR=$IP
  fi
  #
  # Write out the definition for the object and the network it is on.
  #
  OBJECT=`echo $interface | sed 's/[^[:alnum:]]/_/g' | tr [[:lower:]] [[:upper:]]`
  echo "${OBJECT} ${IP} 32 NO" >> netobjects
  OBJECT=${OBJECT}_NET
  echo "${OBJECT} ${NETADDR} ${MASK} YES" >> netobjects
  #
  # If this is the route to the gateway then print the two special objects.
  #
  if [ $interface = $GATEWAYDEV ]; then
    echo "GATEWAY ${GATEWAY} 32 NO" >> netobjects
    echo "GATEWAYNET $NETADDR $MASK NO" >> netobjects
  fi
done
