#!/bin/bash
#
# network	stop, restart, start, the networking

if [ -f /etc/sysconfig/network_cfg ]; then 
	. /etc/sysconfig/network_cfg
else
	echo "/etc/sysconfig/network file not found!!!"
	echo "Major Error, giving up"
	exit -1
fi

# Setting the hostname
echo "Setting hostname...."
hostname $HOSTNAME

if [ "$NETWORKING" != "yes" ]; then 
	echo "NETWORKING turned off..networking functions not enabled"	
	exit 0 
fi 

ifup ()
{
    if [ "$BOOTPROTO" = "dhcp" ]; then
        if [ -f /sbin/pump ]; then
            # If we have pump we prefer it to get an ip number
            echo -n "Determining IP information for $DEVICE...."
            if /sbin/pump -i $DEVICE ; then
                echo " done...."
            else
                echo " failed...."
            fi
        elif [ -f /sbin/dhcpcd ]; then
            # Try to use dhcpcd
            echo -n "Determining IP information for $DEVICE...."
            if /sbin/dhcpcd $DEVICE ; then
                echo " done...."
            else
                echo "failed...."
            fi
        else
            # We don't have a client to get an ip
            echo "Failed to find a client to obtain ip number...."
        fi

    else

        ifconfig ${DEVICE} ${IPADDR} netmask ${NETMASK} broadcast ${BROADCAST}
       #echo "ifconfig ${DEVICE} ${IPADDR} netmask ${NETMASK} broadcast ${BROADCAST}"
    fi
}

ifdown () {
  #kill the dhcpcd clients 
  pid=$( ps -ax | grep "dhcpcd" | grep "$DEVICE" | awk '{print $1}')
  if [ "$pid" != "" ]; then 
     echo "killing dhcpcd pid $pid"
     kill $pid
  fi 
  
  ifconfig ${DEVICE} down 
  echo  "Shutting down device ${DEVICE}"
}

case "$1" in 
   start)
	for i in /etc/sysconfig/ifcfg-*
	do
	 . $i
	 if [ "${ENABLE}" = "yes" ]; then
	   echo "Brining up interface ${DEVICE}.."
           ifup 
	 fi
	done
     	echo "setting kernel IP routing tables"
	#echo "route add default gateway $GATEWAY dev $GW_DEV"
        route add default gateway $GATEWAY dev $GW_DEV
	route add -net 127.0.0.0 netmask 255.0.0.0 dev lo

   ;;
   stop)
    for DEVICE in $(sed -ne'/:/p' /proc/net/dev | awk -F: '{print $1}' )
     do
	echo "shutting down $DEVICE..."
	ifdown
     done
	;;

   restart)
	$0 stop	
	$0 start
	;;
   *)
   	echo "usage: start|stop|restart "
	;;
   esac
   
	
