#!/bin/sh
########################################################################
# Begin $network_devices/ifdown
#
# Description : Interface Down
#
# Authors     : Nathan Coulson - nathan@linuxfromscratch.org
#               Kevin P. Fleming - kpfleming@linuxfromscratch.org
#
# Version     : 00.01
#
# Notes       : the IFCONFIG variable is passed to the scripts found
#               in the services directory, to indicate what file the
#               service should source to get environmental variables.
#
########################################################################

. /etc/sysconfig/rc 
. ${rc_functions} 

# Collect a list of configuration files for our interface
if [ -n "${2}" ]; then
	for file in ${@#$1}; do # All parameters except $1
		FILES="${FILES} ${network_devices}/ifconfig.${1}/${file}"
	done
elif [ -d "${network_devices}/ifconfig.${1}" ]; then
	FILES=`echo ${network_devices}/ifconfig.${1}/*`
else
	FILES="${network_devices}/ifconfig.${1}"
fi

# Reverse the order configuration files are processed in
for file in ${FILES}; do
	FILES2="${file} ${FILES2}"
done
FILES=${FILES2}

# Process each configuration file
for file in ${FILES}; do
	# skip backup files
	if [ "${file}" != "${file%""~""}" ]; then
		continue
	fi

	if [ ! -f "${file}" ]; then
		boot_mesg "${file} is not a network configuration file or directory." ${WARNING}
		echo_warning
		continue
	fi
	(
		. ${file}

		# Will not process this service if started by boot, and ONBOOT
		# is not set to yes
		if [ "${IN_BOOT}" = "1" -a "${ONBOOT}" != "yes" ]; then
			continue
		fi

		# Will not process this service if started by hotplug, and 
		# ONHOTPLUG is not set to yes
		if [ "${IN_HOTPLUG}" = "1" -a "${ONHOTPLUG}" != "yes" ]; then
			continue
		fi
		
		# This will allow us to assign subinterfaces to our primary
		if [ "${INTERFACE}" != "" ]; then
			NET_IF=${INTERFACE}
		else
			NET_IF=${1}
		fi

		# This will run the service script, if SERVICE is set
		if [ "${INTERFACE}" = "" ]; then
			if [ -n "${SERVICE}" -a -x "${network_devices}/services/${SERVICE}" ]; then
				TEST="`ip addr show ${NET_IF} | grep inet | grep ${NET_IF} | cut -f1 -d'/' | cut -f2 -d't' | cut -f2 -d' '`"
				if [ -z "$TEST" ]; then
					boot_mesg "Interface ${NET_IF} already disabled." ${WARNING}
					echo_warning
					continue
				else
					if ip link show ${NET_IF} > /dev/null 2>&1; then
						IFCONFIG=${file} ${network_devices}/services/${SERVICE} ${NET_IF} down
					else
						boot_mesg "Interface ${NET_IF} doesn't exist." ${WARNING}
						echo_warning
					fi
				fi
			else
				boot_mesg -n "Unable to process ${file}.  Either" ${FAILURE}
				boot_mesg -n " the SERVICE variable was not set,"
				boot_mesg " or the specified service cannot be executed."
				echo_failure
				continue
			fi
		fi
	)
done

if [ "${INTERFACE}" = "" ]; then
	if [ -z "${2}" ]; then
		boot_mesg "Bringing down the ${1} interface..."
		ip link set ${1} down
		evaluate_retval
	fi
fi

# End $network_devices/ifdown
