#!/bin/sh

PREREQS=""

prereqs() { echo "$PREREQS"; }

case "$1" in
    prereqs)
    prereqs
    exit 0
    ;;
esac

load_boot_vga_kms()
{
	local boot_file pci_dir alias_string

	for boot_file in /sys/bus/pci/devices/*/boot_vga; do
		[ -f "${boot_file}" ] || continue
		[ "$(cat "${boot_file}")" = "1" ] || continue
		pci_dir=$(dirname "${boot_file}")
		[ -f "${pci_dir}/modalias" ] || continue
		alias_string=$(cat "${pci_dir}/modalias")
		case "${alias_string}" in
			*v00008086*|*v000010DE*|*v00001002*)
				modprobe -q "${alias_string}" 2>/dev/null || true
				;;
			*)
				[ -n "${alias_string}" ] && modprobe -q nouveau 2>/dev/null || true
				;;
		esac
		break
	done
}

if [ -w /sys/kernel/uevent_helper ]; then
	echo > /sys/kernel/uevent_helper
fi

for item in lib lib64 bin sbin; do
	while [ ! -L "/$item" ]; do
		sleep 0.1
	done
done

/bin/mkdir -p /run/vdev/

# Single hotplug-only listener. Existing devices are seeded via vdevadm
# trigger in pci → block → usb order (modprobe constrained by actions.initrd).
/sbin/vdevd -c /etc/vdev/vdevd.initrd.conf /dev

if [ -d /dev/metadata/udev ] && ! [ -e /run/udev ]; then
	/bin/ln -s /dev/metadata/udev /run/udev || true
fi

# Wait for control socket (initrd profile binds it for settle).
_i=0
while [ "${_i}" -lt 50 ]; do
	[ -S /run/udev/control ] && break
	sleep 0.1
	_i=$((_i + 1))
done

# Seed storage with add only (pci → block → usb). Do not trigger bind here:
# add cold-plugs existing nodes; bind/unbind rebind is for real-root input settle.
# vdevd still accepts kernel bind/unbind uevents passively (listener below)
# for late USB/storage hotplug after this loop returns.
for _sub in pci block usb; do
    vdevadm trigger -s "${_sub}" -a add >/dev/null 2>&1 || true
done

load_boot_vga_kms

# If the rootdelay parameter has been set, we wait a bit for devices
# like usb/firewire disks to settle.
if [ "$ROOTDELAY" ]; then
	sleep $ROOTDELAY
fi

# Persist for later initramfs scripts (ORDER runs us in a subshell; bare
# export would be lost before cryptroot/forcelvm).
echo 'export DM_DISABLE_UDEV=1' >> /conf/param.conf
# shellcheck disable=SC1091
[ -e /conf/param.conf ] && . /conf/param.conf

# Ensure device mapper node:
if [ ! -c /dev/mapper/control ]; then
	mkdir -p /dev/mapper
	mknod -m 600 /dev/mapper/control c 10 236 2>/dev/null || true
fi

# Leave vdevd running to process events that come in out-of-band (like USB
# connections)
