#!/bin/sh
### BEGIN INIT INFO
# Provides:          ifplugd
# Required-Start:    
# Required-Stop:     
# Should-Start:      
# Should-Stop:       
# Default-Start:     S
# Default-Stop:      0 6
# Short-Description: Raise network interfaces and monitor link.
### END INIT INFO

PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin"

# functions from /init.d/networking
check_network_file_systems() {
    [ -e /proc/mounts ] || return 0

    if [ -e /etc/iscsi/iscsi.initramfs ]; then
	echo "not deconfiguring network interfaces: iSCSI root is mounted."
	exit 0
    fi

    exec 9<&0 < /proc/mounts
    while read DEV MTPT FSTYPE REST; do
	case $DEV in
	/dev/nbd*|/dev/nd[a-z]*|/dev/etherd/e*)
	    echo "not deconfiguring network interfaces: network devices still mounted."
	    exit 0
	    ;;
	esac
	case $FSTYPE in
	nfs|nfs4|smbfs|ncp|ncpfs|cifs|coda|ocfs2|gfs|pvfs|pvfs2|fuse.httpfs|fuse.curlftpfs)
	    echo "not deconfiguring network interfaces: network file systems still mounted."
	    exit 0
	    ;;
	esac
    done
    exec 0<&9 9<&-
}

check_network_swap() {
    [ -e /proc/swaps ] || return 0

    exec 9<&0 < /proc/swaps
    while read DEV MTPT FSTYPE REST; do
	case $DEV in
	/dev/nbd*|/dev/nd[a-z]*|/dev/etherd/e*)
	    echo "not deconfiguring network interfaces: network swap still mounted."
	    exit 0
	    ;;
	esac
    done
    exec 0<&9 9<&-
}

grep -q "nfsroot" /proc/cmdline
nfsroot=$?

# See how we were called.
case "$1" in
	start)
		# Setup network filtering, taken from init.d networking
		sysctl -e -p /etc/sysctl.conf >/dev/null 2>&1


		for interface in $(cat /etc/network/interfaces | grep iface | sed 's/iface\s\([^\s]*\)inet\s.*$/\1/');
		do 
			echo -n "Interface $interface: "

			ip a s $interface 2>/dev/null | grep -q UP
			interfaceup=$?

			if [ "$interface" == "lo" ] || [ "$interface" == "wlan0" ]; then
				ifconfig $interface > /dev/null 2>&1
				if [ $interfaceup != 0 ]; then
					ifup $interface
					echo started
				else
					echo "already running"
				fi
			else
				if [ $interfaceup != 0 ] && [ $nfsroot != 0 ]; then
					start-stop-daemon -p /var/run/ifplugd.$interface.pid -a ifplugd -S -- -r /etc/ifplugd/ifplugd.action -i $interface;
					echo "started ifplugd service"
				else
					if [ $nfsroot == 0 ]; then
						echo "used for root-over-nfs"
					else
						echo "already running"
					fi
				fi
			fi
		done;
		;;
	stop)
		ip a s lo 2>/dev/null | grep -q UP
		if [ $? == 0 ]; then
			ifdown lo
		fi

		check_network_file_systems
		check_network_swap

		if [ $nfsroot == 0 ]; then
			echo "not deconfiguring network interfaces: root-over-nfs is used"
			exit 0
		fi

		for interface in $(ls /var/run/ifplugd.*.pid 2>/dev/null); 
		do 
			start-stop-daemon -p $interface -K
		done
		;;
	restart)
		$0 stop
		$0 start
		;;
	*)
		echo "Usage: $0 {start|stop|restart}"
		exit 1
esac
exit 0
