# Tiny Cloud - mdev hotplug functions
# vim:set filetype=sh:
# shellcheck shell=sh

# generic helper function to install mdev rules
install_before() {
	local before="$1"
	shift
	local line="$*"

	# already installed
	fgrep -q "$line" /etc/mdev.conf && return 0

	if grep -q "$before" /etc/mdev.conf; then
		# install before existing rule
		line="-$line"
	else
		# no rule exists, put it before the catch-all fallback
		before="^# fallback"
		line="$line\n"
	fi
	sed -i -Ee "s|($before.*)|$line\n\1|" /etc/mdev.conf
}

# hotpluggable VNICs (multi-cloud)
mod__vnic_eth_hotplug() {
	[ -f /lib/mdev/vnic-eth-hotplug ] || return 1

	install_before "^eth" \
		"eth[0-9]	root:root 0644 */lib/mdev/vnic-eth-hotplug"

	# NICs attached at launch don't get added with mdev -s
	assemble-interfaces
}

# load cloud-specific functions
: "${LIBDIR:=$PREFIX/lib}"
if [ -f "$LIBDIR/tiny-cloud/cloud/$CLOUD/mdev" ]; then
	. "$LIBDIR/tiny-cloud/cloud/$CLOUD/mdev"
fi
