#!/bin/sh

WITHOUT_RC_COMPAT=1

# Source function library.
. /etc/init.d/functions

cd /etc/sysconfig/network-scripts
. network-functions

CONFIG=$1

[ -z "$CONFIG" ] && {
    msg_usage "ifdown <device name>"
    exit 1
}

[ -f "$CONFIG" ] || CONFIG="ifcfg-$CONFIG"
[ -f "$CONFIG" ] || {
    msg_usage "ifdown <device name>"
    exit 1
}

if [ "$UID" != 0 ]; then
    if [ -x /usr/sbin/usernetctl ]; then
	if /usr/sbin/usernetctl $CONFIG report ; then
	    exec /usr/sbin/usernetctl $CONFIG down
	fi
    fi
    echo "Users cannot control this device." >&2
    exit 1
fi

source_config
if [ "$IN_HOTPLUG" = "1" ]; then
	is_yes $USE_HOTPLUG || exit 0
fi

. /etc/sysconfig/network-scripts/ifdown-pre $DEVICE

DEVICETYPE=`echo $DEVICE | sed "s/[0-9]*$//"`
OTHERSCRIPT="/etc/sysconfig/network-scripts/ifdown-${DEVICETYPE}"

if [ -x $OTHERSCRIPT ]; then
	exec $OTHERSCRIPT $CONFIG $2
fi

if is_yes "$NETWORKING_IPV6"; then
	/etc/sysconfig/network-scripts/ifdown-ipv6 "$DEVICE"
fi

# Check to make sure the device is actually up
check_device_down && exit 0

DHCPCD=/sbin/dhcpcd
DHCPXD=/sbin/dhcpxd
PUMP=/sbin/pump
retcode=0

if [ "$BOOTPROTO" = pump -o "$BOOTPROTO" = bootp ]; then
	[ -n "`pidof -x pump`" ] && { "$PUMP" -r -i "$DEVICE"; retcode=$?; }
fi

if [ "$BOOTPROTO" = dhcp ]; then
	if [ -x "$DHCPCD" ]; then
		if [ -n "`pidof -x dhcpcd`" ]; then
			"$DHCPCD" -k "$DEVICE"
			retcode=$?
			# workaround for https://bugzilla.altlinux.org/show_bug.cgi?id=5559
			sleep 2
		fi
	elif [ -x /sbin/dhclient ]; then
		if [ -f /var/run/dhclient.pid ]; then
			PID=$(cat /var/run/dhclient.pid)
			if ps ax --no-header |fgrep -qs "$PID"; then
				kill "$PID"
			fi
			retcode=$?
		fi
	elif [ -x "$DHCPXD" ];then
		"$DHCPXD" -k "$DEVICE"
		retcode=$?
	elif [ -x "$PUMP" ];then
		"$PUMP" -r -i "$DEVICE"
		retcode=$?
	fi
fi

# If there is a /var/run/dhcpcd-"$DEVICE", down dhcp
if [ -e "/var/run/dhcpcd-$DEVICE.pid" ]; then
	"$DHCPCD" -k "$DEVICE"
fi

ip link set dev "$DEVICE" down
[ "$retcode" = "0" ] && retcode=$?

# wait up to 5 seconds for device to actually come down...
waited=0
while ! check_device_down && [ "$waited" -lt 500 ]; do
    usleep 10000
    waited=$[waited+1]
done

SBIN_IWCONFIG=/sbin/iwconfig
# don't leave an outdated key sitting around
if [ -n "$WIRELESS_ENC_KEY" -a -x "$SBIN_IWCONFIG" ]; then
	"$SBIN_IWCONFIG" ${DEVICE} enc 0 >/dev/null 2>&1
fi

if [ "$retcode" = 0 ] ; then
    /etc/sysconfig/network-scripts/ifdown-post $CONFIG
    # do NOT use $? because ifdown should return whether or not
    # the interface went down.
fi

exit $retcode
