#!/bin/sh -e

. /lib/lsb/init-functions

MYNAME="${0##*/}"
report() { echo "${MYNAME}: $*" ; }
report_err() { log_failure_msg "$*" ; }
report_debug() { [ "$DEBUG" != yes ] || report "$*" ; }
# 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
# it is used as a variable in this script order to ease transitions 
# to other locations by the package (not by the sysadmin), if you want
# to setup an alternate location please use a symlink
IFSTATE=/etc/network/ifstate

case "$1" in
	start|restart)
		log_begin_msg "Initializing ifupdown state..."
#
# /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.  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
				log_success_msg "${RUN_CANONICALDIR}/..."
				if ! mkdir "$RUN_CANONICALDIR" ; then
					#echo "failed."
					report_err "Failure creating directory $RUN_CANONICALDIR"
					log_end_msg 1
					exit 1
				fi
			else
				#echo "failed."
				report_err "The canonical path of the run directory could not be determined"
				log_end_msg 1
				exit 1
			fi
		fi
# Create the state file
# This signals that ifupdown is available for use
		#echo -n "Initializing: $IFSTATE"
		if ! : > "$IFSTATE" ; then
			#echo "failed."
			report_err "Failure initializing $IFSTATE"
			log_end_msg 1
			exit 1
		fi
		log_end_msg 0
		;;
	stop)
		[ -x /etc/init.d/ifupdown-clean ] && /etc/init.d/ifupdown-clean start
		;;
	force-reload)
		;;
	restart)
		$0 start
		;;
	*)
		echo "Usage: $0 {start|stop|restart|force-reload}" >&2
		exit 3
		;;
esac

exit 0
