#!/bin/sh

PREREQ=""

prereqs()
{
    echo "$PREREQ"
}

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

. /usr/share/initramfs-tools/hook-functions

manual_add_modules 'bcachefs'

# chacha20 and poly1305 are used for encrypted bcachefs filesystems.
add_loaded_modules 'chacha20[-_]*'
add_loaded_modules 'poly1305[-_]*'

# bcachefs keeps its installed path, because the udev rules copied below run
# it by absolute path and that path is whatever ROOT_SBINDIR was. mount(8)
# looks for its helper in /sbin, so that one is placed rather than preserved.
copy_exec /usr/sbin/bcachefs
copy_exec /usr/sbin/mount.bcachefs /sbin/mount.bcachefs

# The udev rules matter here as much as anywhere they're installed. A
# multi-device root comes up in the initramfs, which is precisely where a
# member is most likely to still be enumerating - so without these there is no
# hot-add for a device that arrives late, and no per-member by-uuid symlink
# either, on the one filesystem that can't simply be mounted again later.
#
# Guarded: a missing rules file must not take the whole initramfs build down
# with it. Someone who installed only the binary should get an initramfs
# without hot-add, not no initramfs.
if [ -e /usr/lib/udev/rules.d/64-bcachefs.rules ]; then
	copy_file rules /usr/lib/udev/rules.d/64-bcachefs.rules /lib/udev/rules.d/64-bcachefs.rules
fi

# A bcachefs root is mounted here, by the initramfs's own systemd - so the
# generator that raises the mount timeout has to be here too, or the root
# mount gets DefaultTimeoutStartSec and recovery is killed at 90 seconds.
# A symlink, not a copy: the binary it dispatches through is already above.
if [ -n "/usr/lib/systemd/system-generators" ]; then
	mkdir -p "$DESTDIR/usr/lib/systemd/system-generators"
	ln -sf /usr/sbin/bcachefs "$DESTDIR/usr/lib/systemd/system-generators/bcachefs-mount-generator"
fi
