#!/bin/sh -e

PREREQS=""

prereqs() { echo "$PREREQS"; }

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

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

if [ "${quiet:-n}" = "y" ]; then
	log_level=notice
else
	log_level=info
fi

SYSTEMD_LOG_LEVEL=$log_level /usr/lib/systemd/systemd-udevd --daemon --resolve-names=never

udevadm trigger --type=all --action=add --prioritized-subsystem=block,drm

# Dynamic Root Path Resolution: Parse the target root path using pure shell string manipulation.
# This avoids deadlocks caused by invoking 'blkid' or 'findfs' before devices are fully probed.
WAIT_TARGET=""
if [ -n "$ROOT" ]; then
    case "$ROOT" in
        UUID=*)
            WAIT_TARGET="/dev/disk/by-uuid/${ROOT#UUID=}"
            ;;
        PARTUUID=*)
            WAIT_TARGET="/dev/disk/by-partuuid/${ROOT#PARTUUID=}"
            ;;
        LABEL=*)
            WAIT_TARGET="/dev/disk/by-label/${ROOT#LABEL=}"
            ;;
        PARTLABEL=*)
            WAIT_TARGET="/dev/disk/by-partlabel/${ROOT#PARTLABEL=}"
            ;;
        /dev/*)
            WAIT_TARGET="$ROOT"
            ;;
        *)
            WAIT_TARGET=""
            ;;
    esac
fi

# Precise Convergence: Block execution ONLY until the root device is fully finalized by udev.
# Once the root path appears, the script exits immediately, leaving other non-essential devices
# to finish processing in parallel. Includes a 3-second timeout for distribution safety.
if [ -n "$WAIT_TARGET" ]; then
    /bin/udevadm settle --timeout=3 --exit-if-exists="$WAIT_TARGET" || true
else
    # Fallback to standard full settle if the root format cannot be determined statically
    /bin/udevadm settle --timeout=5 || true
fi

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