#!/bin/sh -e

[ -x /sbin/ifup ] || exit 0
[ -x /sbin/ifdown ] || exit 0

MYNAME="${0##*/}"
report() { echo "${MYNAME}: $*" ; }
report_err() { report "Error: $*" >&2 ; }
# Once the improved readlink program has made it into coreutils,
# /lib/init/ can be removed from the PATH.
PATH=/lib/init:/sbin:/bin:/usr/sbin:/usr/bin
RUN_DIR=/etc/network/run
[ -r /etc/default/ifupdown ] && . /etc/default/ifupdown

# Note: The state file location is hardcoded in ifup|ifdown
IFSTATE=/etc/network/ifstate

case "$1" in
	start|restart)
		if [ "$2" ]; then
			report_err "Arguments to '$1' command not accepted"
			exit 3
		fi
		echo -n "Setting up networking..."
		#
		# /etc/network/run can be either a directory or a symlink
		# to a directory where state information for the ifupdown
		# utility can be stored.  In the latter case we try here
		# to create the directory if it doesn't already exist;
		# this makes it possible for /etc/network/run to be a
		# symlink into a filesystem that is empty at boot time.
		# A common target for the symlink is /dev/shm/network/.
		# The parent of the directory must already exist.
		#
		if [ -L "$RUN_DIR" ] && [ ! -d "$RUN_DIR" ] ; then
			# Target of symlink is not a dir
			# Create directory at the target
			if RUN_CANONICALDIR="$(readlink -f "$RUN_DIR")" && [ "$RUN_CANONICALDIR" ] ; then
				echo -n "${RUN_CANONICALDIR}/..."
				if ! mkdir "$RUN_CANONICALDIR" ; then
					echo "failed."
					report_err "Failure creating directory $RUN_CANONICALDIR"
					exit 1
				fi
			else
				echo "failed."
				report_err "The canonical path of the run directory could not be determined"
				exit 1
			fi
		fi
		# Create the state file
		# Doing this also signals that ifupdown is available for use
		if ! : > "$IFSTATE" ; then
			echo "failed."
			report_err "Failure initializing $IFSTATE"
			exit 1
		fi 
		echo "done."
		exit 0
		;;
	stop)
		if [ "$2" ]; then
			report_err "Arguments to '$1' command not accepted"
			exit 3
		fi
		[ -x /etc/init.d/ifupdown-clean ] && /etc/init.d/ifupdown-clean start
		;;
	force-reload)
		;;
	*)
		echo "Usage: $0 {start|stop|restart|force-reload}" >&2
		exit 3
		;;
esac

exit 0
