#!/bin/sh
PATH=/sbin:/usr/sbin:/bin:/usr/bin
TEXTDOMAIN=initscripts
cd /etc/sysconfig/network-scripts
. ./network-functions
IFSTAT_DOWN_FILE="$IFSTAT_FILENAME_BASE${1}"
echo "bringdown" > $IFSTAT_DOWN_FILE
CONFIG=$1
[ -z "$CONFIG" ] && {
    echo $"usage: ifdown <device name>" >&2
    exit 1
}
need_config $CONFIG
[ -f "$CONFIG" ] || {
    echo $"$0: configuration for ${1} not found." >&2
    exit 1
}
source_config
DEVICETYPE=`echo $DEVICE | sed "s/[0-9]*$//"`
. /etc/sysconfig/network
if [  "$VLAN" = "yes" ]; then
    if [ ! -f /proc/net/vlan/${DEVICE} ] ; then
        echo "VLAN ${DEVICE} already down"
        echo "down" > $IFSTAT_DOWN_FILE
        exit 1
    fi
else
    check_device_down ${DEVICE} && [ "$BOOTPROTO" != "dhcp" ] && { 
        echo "Device ${DEVICE} already down"
        echo "down" > $IFSTAT_DOWN_FILE
        exit 1
    }
fi
if [ -f /proc/net/vlan/${DEVICE}.* ] ; then
    echo "The following VLAN's are operating on this interface:"
    for device in `/bin/ls /proc/net/vlan/${DEVICE}.*` ; do
       echo "${device##*/}"
    done
    echo "Please bring down these VLANs before bringing down this interface"
    exit 1
fi
if [ -n "${HWADDR}" ]; then
    FOUNDMACADDR=`LC_ALL= LANG= /sbin/ip -o link show ${DEVICE} | \
	sed 's/.*link\/ether \([[:alnum:]:]*\).*/\1/'`
    if [ "${FOUNDMACADDR}" != "${HWADDR}" ]; then
        NEWCONFIG=`fgrep -l "HWADDR=${HWADDR}" /etc/sysconfig/network-scripts/ifcfg-*`
	if [ -n "${NEWCONFIG}" ]; then
	   exec /sbin/ifdown ${NEWCONFIG}
	else
	   echo $"Device ${DEVICE} has different MAC address than expected, ignoring."
	   exit 1
	fi
    fi
fi
retcode=0
check_default_gateway ${DEVICE}
if [ "$BOOTPROTO" = dhcp ]; then
    get_current_ip ${DEVICE}
    stop_dynamic_networking ${DEVICE}
    remove_assigned_servers ${DEVICE} 
fi
echo $"Flushing all addresses associated with ${DEVICE}"
/sbin/ip addr flush dev ${DEVICE} 2>/dev/null
echo $"Bringing down ${DEVICE}, please wait."
/sbin/ip link set ${DEVICE} down
[ "$retcode" = "0" ] && retcode=$?
waited=0
while ! check_device_down ${DEVICE} && [ "$waited" -lt 50 ] ; do
    usleep 10000
    waited=$(($waited+1))
done
del_policy_route ${DEVICE}
if [ -f /proc/net/vlan/${DEVICE} ] ; then
      echo "Removing VLAN"
      vconfig rem ${DEVICE} || {        
          echo $"ERROR: could not remove VLAN device ${DEVICE}"
          exit 1
      }
      try_count=0
      echo "Waiting for VLAN ${DEVICE} to disappear: "
      while [ -f /proc/net/vlan/${DEVICE} ] && [ $try_count -lt 10 ]
      do 
          echo -n "."
          sleep 1
          try_count=$(($try_count+1))
      done
fi
echo "Done bringing down ${DEVICE}"
echo "down" > $IFSTAT_DOWN_FILE
exit $retcode
