#!/bin/bash

# Bring interfaces up and down. Used by the systemd unit and by the
# OpenRC, s6-rc and 66 services shipped in the package.
# Those supervisors call start, stop and reload. A restart is stop then start.

RUN_DIR="/run/network"
IFSTATE_LOCKFILE="${RUN_DIR}/ifstatelock"

STATE_DIR="/var/tmp/network"
IFSTATE_FILE="${STATE_DIR}/ifstatenew"

NAME=networking

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

CONFIGURE_INTERFACES=yes

EXTRA_ARGS=
EXTRA_ARGS=

[ "$VERBOSE" = yes ] && EXTRA_ARGS=-v
[ "$DEBUG" = yes ] && EXTRA_ARGS="$EXTRA_ARGS -d"
[ "$SYSLOG" = yes ] && EXTRA_ARGS="$EXTRA_ARGS --syslog"

perf_options() {
    # At bootup lets set perfmode
    [ -f ${IFSTATE_LOCKFILE} ] && echo -n "" && return

    echo -n "--perfmode"
}

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

check_network_file_systems() {
    [ -e /proc/mounts ] || return 0

    if [ -e /etc/iscsi/iscsi.initramfs ]; then
	echo ${NAME}':' "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*)
	    echo ${NAME}':' "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 ${NAME}':' "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 ${NAME}':' "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 2>/dev/null)
			    do
				    link=${iface##:*}
				    link=${link##.*}
				    if [ -e "/sys/class/net/$link" ]
				    then
				        echo "$iface"
				    fi
			    done)
	    if [ -n "$ifaces" ]
	    then
		ifup $ifaces "$@" || true
	    fi
    fi
}

ifup_mgmt () {
	ifaces=$(ifquery --list --allow=mgmt 2>/dev/null)
	if [ -n "$ifaces" ]; then
		echo "bringing up mgmt class interfaces"
		ifup --allow=mgmt
	fi
}

ifupdown_init() {
	# remove state file at boot
	[ ! -e ${IFSTATE_LOCKFILE} ] && rm -f ${IFSTATE_FILE}

	[ ! -e /run/network ] && mkdir -p /run/network &>/dev/null
	[ ! -e /etc/network/run ] && \
		ln -sf /run/network /etc/network/run &>/dev/null
}

# Halt, reboot or poweroff is already in progress.
# systemctl is consulted only when /run/systemd/system exists.
sysreset_in_progress() {
	local _softlevel _runlevel _rl _systemctl _pid _cmd _i

	# openrc-run exports the runlevel it is entering before it stops
	# services. This layout also passes through "off" on the way down
	# and may use a "reboot" runlevel.
	case "${RC_RUNLEVEL:-}" in
		shutdown|reboot|off) return 0 ;;
	esac
	if [ -r /run/openrc/softlevel ]; then
		read -r _softlevel < /run/openrc/softlevel || true
		case "${_softlevel:-}" in
			shutdown|reboot|off) return 0 ;;
		esac
	fi

	# Present only when systemd is pid 1 (or was started as the supervisor).
	if [ -d /run/systemd/system ]; then
		for _systemctl in /bin/systemctl /usr/bin/systemctl; do
			[ -x "$_systemctl" ] || continue
			"$_systemctl" list-jobs 2>/dev/null \
				| grep -qE '(shutdown|reboot|halt|poweroff)\.target'
			return $?
		done
		return 1
	fi

	# sysvinit: current runlevel 0 is halt, 6 is reboot.
	# "runlevel" prints "previous current"; only the current field counts.
	_runlevel=/sbin/runlevel
	[ -x "$_runlevel" ] || _runlevel=$(command -v runlevel 2>/dev/null || true)
	if [ -n "$_runlevel" ] && [ -x "$_runlevel" ]; then
		_rl=$("$_runlevel" 2>/dev/null) || true
		set -- $_rl
		case "${2:-}" in
			0|6) return 0 ;;
		esac
	fi

	# s6-linux-init and 66 run the down script as a descendant of the
	# shutdown program. A manual stop has no such ancestor.
	_pid=$$
	_i=0
	while [ "$_pid" -gt 1 ] && [ "$_i" -lt 32 ]; do
		_i=$((_i + 1))
		_cmd=$(tr '\0' ' ' < /proc/$_pid/cmdline 2>/dev/null) || break
		case "$_cmd" in
			*rc.shutdown*|*s6-linux-init-shutdownd*|*66-shutdown*|*66-hpr*)
				return 0
				;;
		esac
		_pid=$(sed -n 's/^PPid:[[:space:]]*//p' /proc/$_pid/status 2>/dev/null) || break
		[ -n "$_pid" ] || break
	done

	return 1
}

case "$1" in
start)
	ifupdown_init
	if [ "$CONFIGURE_INTERFACES" = no ]
	then
	    echo ${NAME}':' "Not configuring network interfaces, see /etc/default/networking"
	    exit 0
	fi
	set -f
	exclusions=$(process_exclusions)
	perfoptions=$(perf_options)
	echo ${NAME}':' "Configuring network interfaces"
	ifup_mgmt
	ifup -a $EXTRA_ARGS $exclusions $perfoptions
	ifup_hotplug $HOTPLUG_ARGS $EXTRA_ARGS $exclusions
	;;
stop)
	if [ "$SKIP_DOWN_AT_SYSRESET" = "yes" ]; then
		if sysreset_in_progress; then
			echo ${NAME}':' "Skipping deconfiguring network interfaces"
			exit 0
		fi
	fi
	ifupdown_init
	check_network_file_systems
	check_network_swap
	exclusions=$(process_exclusions)

	echo ${NAME}':' "Deconfiguring network interfaces"
	ifdown -a $EXTRA_ARGS $exclusions
	;;

reload)

	ifupdown_init
	exclusions=$(process_exclusions)

	echo ${NAME}':' "Reloading network interfaces configuration"
	ifreload -a $EXTRA_ARGS $exclusions
	;;

*)
	echo ${NAME}':' "Usage: $0 {start|stop|reload}"
	exit 1
	;;
esac

exit 0
