#!/bin/sh

# initramfs-tools hook: ship the OCI block-device udev sorting script in
# the ramdisk.
#
# The 65-sdx-order.rules rule (KERNEL=="sd*[!0-9]|sr*" PROGRAM="/usr/bin/
# oci-block-device-udev-sorting" SYMLINK+="disk/oci-sort/%c") is copied
# into every initramfs by initramfs-tools, as it lives in
# /etc/udev/rules.d. Its PROGRAM however wasn't: the rule always failed
# while running from the ramdisk, and the /dev/disk/oci-sort symlinks
# only appeared after the main system's udev coldplug. Since the kernel
# sdX naming is NOT deterministic at boot time (the SCSI scan is
# asynchronous), anything enumerating the disks before that coldplug
# (eg: the OCI agent in the live environment, which reports the disk
# names used later by /etc/oci/data-disks) could see and record the
# non-deterministic sdX names, breaking the disk ordering fix.
#
# With the script in the ramdisk, the symlinks are created as soon as
# the disks are discovered, and the /dev devtmpfs (and its symlinks)
# survives the switch_root, so the sorting is effective from the very
# beginning, in the live environment as well as in the installed OS.

PREREQ=""
prereqs () {
	echo "${PREREQ}"
}
case "${1}" in
prereqs)
	prereqs
	exit 0
	;;
esac
. /usr/share/initramfs-tools/hook-functions

# The udev rule runs the script through its shebang (#/bin/bash), which
# isn't part of the busybox-only ramdisk.
copy_exec /bin/bash
copy_exec /usr/bin/oci-block-device-udev-sorting
# dmidecode reads the chassis identification, which decides which
# sorting table to use.
copy_exec /usr/sbin/dmidecode
# The script serializes its storcli queries with flock, and logs with
# logger; use the real binaries, as the busybox applets may not all be
# available in the ramdisk.
copy_exec /usr/bin/flock
copy_exec /usr/bin/logger || true

# Be explicit about the rule: it normally gets in the initramfs by
# itself, but make sure it does.
copy_file udev /etc/udev/rules.d/65-sdx-order.rules /usr/lib/udev/rules.d/65-sdx-order.rules

exit 0
