[Main]
Type = oneshot
Version = 0.2.0
Description = "vdev-coldplug oneshot (native 66; same role as eudev udevadm)"
User = ( root )
Depends = ( vdevd )
Options = ( !log )

[Start]
Execute = (
	s6-envdir /run/vdev/env

	multisubstitute
	{
		importas -i VDEV_BIN VDEV_BIN
		importas -i VDEV_CONFIG_DIR VDEV_CONFIG_DIR
		importas -i VDEV_TERMINAL VDEV_TERMINAL
		importas -i VDEV_MOUNTPOINT VDEV_MOUNTPOINT
		importas -i VDEV_STAMP_DIR VDEV_STAMP_DIR
		importas -i VDEV_EARLY_STAMP VDEV_EARLY_STAMP
		importas -i VDEV_LONG_RUNNING VDEV_LONG_RUNNING
		importas -D "" VDEV_EARLY_SUBSYSTEMS VDEV_EARLY_SUBSYSTEMS
		importas -D 15 VDEV_EARLY_SETTLE_TIMEOUT VDEV_EARLY_SETTLE_TIMEOUT
	}
	
	# Ensure that the locks/stamps directory exists before locking
	foreground { mkdir -p $VDEV_STAMP_DIR }

	# Exclusive atomic lock: the second process waits here without running in parallel
	s6-setlock ${VDEV_STAMP_DIR}/coldplug.lock

	# Optional KMS fallback; failures must not fail the oneshot.
	foreground {
		/bin/sh -c "test -r /lib/vdev/vdev-boot-vga-kms.sh &&
					. /lib/vdev/vdev-boot-vga-kms.sh &&
					load_boot_vga_kms;
					exit 0
		"
	}

	# Wait until the supervised listener answers on the control socket
	# (same pattern as eudev's udevadm oneshot waiting for /run/udev/control).
	foreground {
		loopwhilex
		ifelse { vdevadm control --print-pid }
		{ exit 1 }
		sleep 0.2
	}

	# Seed from vdevd.early.conf subsystems= (via vdev-env), promote, then
	# batched remaining trigger (no monolithic --sysfs).
	foreground {
		/bin/sh -c "
			for _s in ${VDEV_EARLY_SUBSYSTEMS}; do
				vdevadm trigger -s ${_s} -a add || true
			done;
			vdevadm settle -t ${VDEV_EARLY_SETTLE_TIMEOUT};
			touch ${VDEV_EARLY_STAMP};
			exit 0
		"
	}
	
	foreground { 
		# Promote early listener to long-running
		if { vdevadm control --promote=${VDEV_LONG_RUNNING} }
		# Fallback: coldplug_only (-1, no -f) already detaches.
		"$VDEV_BIN" -1 -c "${VDEV_CONFIG_DIR}"/"$VDEV_TERMINAL" "$VDEV_MOUNTPOINT"
	}
)
