#!/sbin/openrc-run

# Copyright: 2026 Matthias Geiger <werdahias@debian.org>
# License: GPL-3.0-only
# Inspired by /etc/init.d/networking

name="ifupdown networking"
description="Start/stop network interfaces using ifupdown"

RUNDIR="/run/network"

IFUP=/sbin/ifup
IFDOWN=/sbin/ifdown
IFQUERY=/sbin/ifquery
IFSTATE="$RUNDIR/ifstate"

depend()
{
	need localmount
	after bootmisc
	provide net

}

start_pre()
{
	checkpath -d -m 0755 -o root:netdev "$RUNDIR"
	checkpath -f "$IFSTATE"
}

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
}

start()
{
	ebegin "Bringing up network interfaces with ifupdown"
	$IFUP --all && ifup_hotplug
	eend $? "Failed to bring up interfaces"
	
}

stop()
{
	ebegin "Deconfiguring network interfaces"
	$IFDOWN --all --exclude=lo
	eend $? "Failed to bring down interfaces"
}

reload()
{
	einfo "Reloading network configuration"
	stop
	start
}

status()
{
	# Show status of auto interfaces
	AUTO_INTERFACES=$($IFQUERY --list --allow=auto 2>/dev/null)
	if [ -z "$AUTO_INTERFACES" ]; then
		echo "No auto interfaces configured."
		return 3
	fi

	any_down=0
	for iface in $AUTO_INTERFACES; do
		if $IFQUERY --state "$iface" >/dev/null 2>&1; then
			echo "$iface: up"
		else
			echo "$iface: down"
			any_down=1
		fi
	done

	if [ $any_down -eq 0 ]; then
		return 0  # all up
	else
		return 1  # some down
	fi

}
