#!/bin/sh -e

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

[ -x "$(command -v ifup)" ] || exit 0
[ -x "$(command -v ifdown)" ] || exit 0

# List available fstab files, including any files in /etc/fstab.d.
# This looks ugly, but we can't use find and it's safer than globbing.
fstab_files()
{
    echo /etc/fstab
    if [ -d /etc/fstab.d ]; then
        ls -1 /etc/fstab.d | grep '\.fstab$' | sed -e 's;^;/etc/fstab.d/;'
    fi
}

process_exclusions() {
    set -- $EXCLUDE_INTERFACES
    exclusions=""
    for d
    do
	exclusions="-X $d $exclusions"
    done
    echo $exclusions
}

process_options() {
    [ -e /etc/network/options ] || return 0
    echo "/etc/network/options still exists and it will be IGNORED! Please use /etc/sysctl.conf instead."
}

check_ifstate() {
    if [ ! -d "$RUN_DIR" ] ; then
	if ! mkdir -p "$RUN_DIR" ; then
	    echo "can't create $RUN_DIR"
	    exit 1
	fi
	if ! chown root:netdev "$RUN_DIR" ; then
	    echo "can't chown $RUN_DIR"
	fi
    fi
    if [ ! -r "$IFSTATE" ] ; then
	if ! :> "$IFSTATE" ; then
	    echo "can't initialise $IFSTATE"
	    exit 1
	fi
    fi
}

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

    while read DEV MTPT FSTYPE REST; do
	case $DEV in
	/dev/nbd*|/dev/nd[a-z]*|/dev/etherd/e*|curlftpfs*)
	    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 < /proc/mounts
}

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

    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 < /proc/swaps
}

ifup_hotplug () {
    if [ -d /sys/class/net ]
    then
	    ifaces=$(for iface in $(ifquery --list --allow=hotplug)
			    do
				    link=${iface%%:*}
				    link=${link%%.*}
				    if [ -e "/sys/class/net/$link" ] && ! ifquery --state "$iface" >/dev/null
				    then
					echo "$iface"
				    fi
			    done)
	    if [ -n "$ifaces" ]
	    then
		ifup $ifaces "$@" || true
	    fi
    fi
}

process_options
check_ifstate

if [ "$CONFIGURE_INTERFACES" = no ]
then
    log_action_msg "Not configuring network interfaces, see /etc/default/networking"
    exit 0
fi
set -f
exclusions=$(process_exclusions)
log_action_begin_msg "Configuring network interfaces"
if [ -x "$(command -v udevadm)" ]; then
	if [ -n "$(ifquery --list --exclude=lo)" ] || [ -n "$(ifquery --list --allow=hotplug)" ]; then
		udevadm settle || true
	fi
fi

ifup -a $exclusions $verbose && ifup_hotplug $exclusions $verbose

:
