#!/bin/sh
# FILE:/usr/sbin/ifup-eth
# Copyright (C) 2012 GuoWenxue <guowenxue@gmail.com QQ:281143292>
# This file used to configure the specified network interface device

#--------------------------------------------------
#     Function definition here 
#--------------------------------------------------

#Check arguments $1 is bonding device or not
is_bonding_device()
{
   [ -f /sys/class/net/$1/bonding/slaves ]
}

#Check bonding running or not
is_bonding_running()
{
   if [ ! -f /sys/class/net/$1/bonding/slaves ] ; then
      #Bonding device not exist
      return 1
   fi
   
   for devcfg in $(egrep -l "^[[:space:]]*DEVICE=\"?$1\"?" ifcfg-*) ; do
      onboot=$(awk -F "=" '/ONBOOT/{print $2}' $devcfg) 
      onboot=$(echo $onboot | awk '{ print toupper($0) }')
      if [ "$onboot" = "YES" ] ; then
          return 0
      else       
          return 1
      fi
   done
}

#stop DHCP client or server work on this network adapter
stop_dhcp()
{
   dhcp_pid=`ps | grep -v grep | grep "dhcp" | grep $DEVICE | awk '{print $1;}'` 
   if [ -n "$dhcp_pid" ] ; then
       kill $dhcp_pid
   fi
}

#--------------------------------------------------
#     Script body start here 
#--------------------------------------------------

if [ -z "$network_cfg_dir" ];  then
   export network_cfg_dir=/apps/etc/network
fi

#Call this shell script argument, which should be eth0,eth1,bond0,wlan0...
DEVICE=${1}

[ -z "${DEVICE}" ] && {
   echo $"Usage: $0 <device name>" >&2
   exit 1
}

if [ ! -d $network_cfg_dir -o ! -f "$network_cfg_dir/ifcfg-${DEVICE}" ]; then 
   echo "$0: configuration<$network_cfg_dir/ifcfg-${DEVICE}> not found." >&2 
   echo "Usage: $0 <device name>" >&2 
   exit 1
fi

cd $network_cfg_dir
. ifcfg-${DEVICE}

#Set MAC address
if [ -n "$HWADDR" ] ; then
   HWADDR=$(echo $HWADDR | awk '{ print toupper($0) }')

   #Set Hardware MAC address must sure the adapter is down
   ip link set dev $DEVICE down
   sleep 1
   ip link set dev $DEVICE address $HWADDR
fi

echo "Enable network interface $DEVICE[$NAME]." >&2 

#If it's bonding device, then we set bond arguments
if is_bonding_device ${DEVICE} ; then

   #Bring up all the bonding slave devices and add them to slaves
   #for devcfg in $(egrep -l "^[[:space:]]*MASTER=\"?${DEVICE}\"?" ifcfg-*) ; do
   #   device=$(awk -F "=" '/DEVICE/{print $2}' $devcfg)
   #   ifup-eth $device
   #done
 
   # Add bonding options to bonding master device, must make sure it's down
   ip link set dev ${DEVICE} down
   for arg in $BONDING_OPTS ; do                                  
       key=${arg%%=*};                                            
       value=${arg##*=};                                           
       
       if [ "$key" = "arp_ip_target" ] ; then 
          OLDIFS=$IFS;                       
          IFS=',';                           
          
          for arp_ip in $value; do           
              grep -wq "$arp_ip" /sys/class/net/${DEVICE}/bonding/$key || { 
                  echo +$arp_ip > /sys/class/net/${DEVICE}/bonding/$key      
              }                                                             
          done                                                            
          IFS=$OLDIFS;                                                    
       else                                                                
          echo $value > /sys/class/net/${DEVICE}/bonding/$key             
       fi                                                                  
   done            
   ip link set dev ${DEVICE} up
fi

#If the device is the bonding slave device, add it into the bonding master
if is_bonding_running $MASTER -a [ "${SLAVE}" = yes ] ; then
   ip address flush ${DEVICE}
   ip link set dev ${DEVICE} down
   grep -wq "${DEVICE}" /sys/class/net/${MASTER}/bonding/slaves || {
      echo "+${DEVICE}" > /sys/class/net/${MASTER}/bonding/slaves 2>/dev/null
   }   

   #Query in the master configure file, add myself to primary if it's set.
   for devcfg in $(egrep -l "^[[:space:]]*DEVICE=\"?${MASTER}\"?" ifcfg-*) ; do
      grep "primary=$DEVICE" -r $devcfg >/dev/null 2>&1 && {                                                     
          echo $DEVICE > /sys/class/net/$MASTER/bonding/primary
      }           
   done      

   ip link set dev ${DEVICE} up
   exit 0
fi

# Activate the network adapter
stop_dhcp
ip link set dev $DEVICE up

#If enable DHCP configure or IP address not configured, then use DHCP get IP address and exit
if [ -n "$BOOTPROTO" -o -z "$IPADDR" ]; then
   BOOTPROTO=$(echo $BOOTPROTO | awk '{ print toupper($0) }')
   if [ "$BOOTPROTO" = "DHCP" ] ; then
      udhcpc -i $DEVICE &
      exit
   fi
fi

# Calculate the network configuration value
if [ -z "${NETMASK}" ] ; then 
   eval $(/bin/ipcalc --netmask ${IPADDR}) 
fi
    	    
if [ -z "${PREFIX}" ] ; then 
   eval $(/bin/ipcalc --prefix ${IPADDR} ${NETMASK}) 
fi  

if [ -z "${NETWORK}" ] ; then 
   eval $(/bin/ipcalc --network ${IPADDR} ${NETMASK}) 
fi

#Check this IP Address uesed or not
#if ! /bin/arping -q -c 1 -w 3 -D -I $DEVICE $IPADDR ; then 
#   echo $"Error, some other host already uses address ${IPADDR}."
#fi
   
#Set the IP address
ip addr flush label ${DEVICE}   
if ! ip addr add local ${IPADDR}/${PREFIX} dev ${DEVICE} brd + label ${DEVICE}; then
   echo $"Error adding address ${IPADDR} for ${DEVICE}."
fi

#Set all other multiple bind IP address
for i in $(seq 0 10) ; do
   unset ip NETMASK 
   ip=$(eval "echo \$IPADDR${i}")
   NETMASK=$(eval "echo \$NETMASK${i}")
   
   if [ -n "$ip" ]; then
       if [ -z "$NETMASK" ]; then
            eval $(/bin/ipcalc --netmask ${ip})
       fi
       ip addr flush label ${DEVICE}:${i}
       ifconfig ${DEVICE}:${i} ${ip} netmask ${NETMASK} up
   fi
done
                               

#Set the default route
DEFROUTE=$(echo $DEFROUTE | awk '{ print toupper($0) }')
if [ -n "$GATEWAY" -a "$DEFROUTE" = "YES" ]; then
   #ip route add  ${NETWORK}/${PREFIX} via $GATEWAY > /dev/null 2>&1
   ip route replace default via $GATEWAY
fi

#Enable DHCP server
DHCP_SERVER=$(echo $DHCP_SERVER | awk '{ print toupper($0) }')
if [ -n "$DHCP_SERVER" -a "$DHCP_SERVER" = "YES" ]; then

   conf_file="/tmp/udhcpd_${DEVICE}.conf"
   lease_file="/tmp/udhcpd_${DEVICE}.leases"
   pid_file="/var/run/udhcpd_${DEVICE}.pid"
   
   echo "interface $DEVICE" > $conf_file
   echo "start $DHCP_START_IP" >> $conf_file
   echo "end $DHCP_END_IP" >> $conf_file
   echo "lease_file $lease_file" >> $conf_file
   echo "max_leases 90" >> $conf_file
   echo "pidfile $pid_file" >> $conf_file
   
   if [ -n "$DHCP_NETMASK" ] ; then
     echo  "opt subnet $DHCP_NETMASK" >> $conf_file
   fi
   
   if [ -n "$DHCP_GATEWAY" ] ; then
     echo  "opt router $DHCP_GATEWAY" >> $conf_file
   fi
   
   if [ -n "$DHCP_DNS1" ] ; then
     echo  "opt dns $DHCP_DNS1" >> $conf_file
   fi
   
   if [ -n "$DHCP_DNS1" ] ; then
     echo  "opt dns $DHCP_DNS2" >> $conf_file
   fi
   
   if [ -n "$DHCP_DNS2" ] ; then
     echo  "opt lease $DHCP_LEASE" >> $conf_file
   fi
   
   touch $lease_file
   udhcpd $conf_file
fi
