#!/bin/bash

unset WINDOW # defined by screen, conflicts with our usage

. /etc/init.d/functions

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

[ -f /etc/sysconfig/network ] && . /etc/sysconfig/network

CONFIG=$1

[ -z "$CONFIG" ] && {
    echo $"usage: ifdown <device name>" >&2
    exit 1
}

need_config "${CONFIG}"

[ -f "$CONFIG" ] || {
    echo $"usage: ifdown <device name>" >&2
    exit 1
}

source_config

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

is_nm_enabled

if [ -n "$IN_HOTPLUG" ] && [ "${HOTPLUG}" = "no" -o "${HOTPLUG}" = "NO" ]; then
    exit 0
fi
# networkmanager stuff
# ---------------------------------------------------------------------------------------
if is_true "$_use_nm"; then
 if [ -z "$DEVICE" ]; then
    DEVICE=$(nmcli -t --fields uuid,device con show --active | awk -F ':' "\$1 == \"$UUID\" { print \$2 }")
 fi
  if [ -z "$NAME" ]; then
        NAME=$(echo "System $DEVICE")
  fi
   if [ -n "$DEVICE" ] && ! is_nm_device_unmanaged "$DEVICE" ; then
    if ! LC_ALL=C nmcli -t -f STATE,DEVICE dev status | grep -Eq "^(failed|disconnected|unmanaged|unavailable):$DEVICE$"; then
            nmcli conn down "$NAME"
            exit $?
    fi
        exit 0
   fi
fi

if is_wireless_device "$DEVICE" && [ ! -z "$TYPE" ]; then
        exit 0
fi
# ---------------------------------------------------------------------------------------
if [ -x /sbin/ifdown-pre-local ]; then
    /sbin/ifdown-pre-local ${DEVICE}
fi
OTHERSCRIPT="/etc/sysconfig/network-scripts/ifdown-${DEVICETYPE}"

if [ ! -x ${OTHERSCRIPT} ]; then
    OTHERSCRIPT="/etc/sysconfig/network-scripts/ifdown-eth"
fi

if is_false "$_use_nm" || [ -z "$TYPE" ] || [ "${NM_CONTROLLED}" = "no" ]; then
exec ${OTHERSCRIPT} ${CONFIG} $2
fi
