#!/bin/bash
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: Copyright 2023 SUSE LLC
set -e
shopt -s nullglob

export LC_ALL=C

# The five secrets can arrive in the environment.  A prefix assignment
# (VAR=value sdbootutil) limits them to this process.  But this script
# runs systemd-cryptenroll, systemd-pcrlock, cryptsetup and dracut.  A
# child inherits the whole environment, so each child would carry the
# secret in /proc/PID/environ.  It stays readable there while the child
# lives, and dracut lives for minutes.  So the values are copied into
# plain shell variables, and the exported ones are unset.  The secrets
# then stay in this process.  A child only sees what is given to it on
# purpose, as `enroll_password` does with NEWPASSWORD
#
# "unset" removes the names from the export list.  Assigning an empty
# value would still export the name
#
# This is done here, and not with the other globals below, for two
# reasons.  It must run before the first child (`uname`, a few lines
# down).  It must also run before the `set -x` of --start-trace-code,
# that would write these assignments to the log
env_current_pw="$CURRENT_PW"
env_key="$KEY"
env_pw="$PW"
env_pin="$PIN"
env_recovery_pin="$RECOVERY_PIN"
unset CURRENT_PW KEY PW PIN RECOVERY_PIN

DEBUG_LOG="/var/log/sdbootutil.log"
verbose=

# Replaced with the package version by the spec file
version="1+git20261127.1ef4f50"

# The functions that handle secrets keep them out of the trace (see
# "Secrets and --start-trace-code").  But one missed function is enough
# to leak a secret.  So the log is always created with mode 0600, and
# never with the current umask
if [[ "$*" =~ "--start-trace-code" ]] && ! (umask 077; touch "$DEBUG_LOG") 2>/dev/null; then
	echo "Cannot enable the code trace, $DEBUG_LOG is not writable" >&2
	exit 1
fi
if [[ "$*" =~ "--stop-trace-code" ]] && ! rm -f "$DEBUG_LOG" 2>/dev/null; then
	echo "Cannot disable the code trace, $DEBUG_LOG cannot be removed" >&2
	exit 1
fi
# The trace is only enabled if the log can be opened for writing.  This
# way a trace left behind by root does not break the tool for the other
# users.  The mode is set again on every run.  So a log created by hand,
# or by an older version, is made private before anything is written to
# it.  If the mode cannot be set, the trace stays off.  The completion
# data never enables the trace, as the messages and the trace break the
# shell completion
if [ "$1" != "_print_bash_completion_data" ] && [ -f "$DEBUG_LOG" ] && { chmod 0600 "$DEBUG_LOG" && exec 3>>"$DEBUG_LOG"; } 2>/dev/null; then
	verbose=3
	echo "The trace of the code is being stored in $DEBUG_LOG" >&2
	echo "Remove the file or use --stop-trace-code to stop tracing the code" >&2
	echo "Audit the file before sharing, as secrets can be leaked" >&2
	export BASH_XTRACEFD=3
	export PS4='+ \D{%F %T} ${BASH_SOURCE##*/}:${LINENO}:${FUNCNAME[0]:-main}: '
	set -x
fi

nl=$'\n'
shimdir="/usr/share/efi/$(uname -m)"
arg_esp_path="$SYSTEMD_ESP_PATH"
arg_entry_token=
arg_arch=
arg_all_entries=
arg_entry_keys=()
arg_no_variables=
arg_no_reuse_initrd=
arg_no_random_seed=
arg_portable=
arg_secure_boot=
arg_sync=
arg_only_default=
arg_default_snapshot=
arg_ask_key=
arg_ask_pin=
arg_ask_recovery_pin=
arg_ask_pw=
arg_ask_current_pw=
arg_method=
arg_no_measure_pcr=
arg_pcr=
arg_rootfs=
arg_rootfs_data=
arg_esp_free_space=
arg_devicetree_source=
arg_force=
arg_strict=
arg_disable_predictions=
arg_full=
arg_repair=
have_snapshots=
in_buildroot=
# Snapshot that owns the "/" subvolume.  It is not always the snapshot
# that provides /usr (see `detect_applied_snapshot`)
running_snapshot=
# Snapshot that `transactional-update apply` mounts over the running
# system (see `detect_applied_snapshot`)
applied_snapshot=
# Possible values: vmlinuz image vmlinux linux bzImage uImage Image zImage
image=
unlock_method=
# Set by `get_device_password`
device_pw=

chroot_dir=

# The output goes to a terminal.  A person reads it, so it can have
# colors and extra decorations.  When another program captures the
# output, only the plain data is printed.  `transactional-update` reads
# `list-entries` with `popen` and opens the result as a file name.
# `weak-modules2` parses `show-entry` with a command substitution
interactive=
[ ! -t 1 ] || interactive=1

color_red=
color_end=
# SYSTEMD_COLORS can only disable the colors, as the help message says.
# A forced "true" is ignored.  The programs above inherit the variable
# from the environment of the caller, and the colors would put escape
# sequences in their input
if [ -n "$interactive" ] \
    && [ "$SYSTEMD_COLORS" != "false" ] && [ "$SYSTEMD_COLORS" != "0" ]; then
	color_red="\e[31m"
	color_green="\e[32m"
	color_yellow="\e[33m"
	color_bu="\e[1;4m" # bold underscore
	color_end="\e[m"
fi

# State file for transactional systems
state_file="/var/lib/misc/transactional-update.state"

# Files that sdbootutil installed in the ESP, see `verify_esp_files`
esp_files="/var/lib/sdbootutil/esp-files"

update_predictions=
# Set only when "update-predictions" is the command.  This tells it
# apart from the predictions that another command makes as a side effect

tracked_devices=()

rollback=()

# Set by `enroll` while /etc/crypttab already asks for an unlock method
# that no keyslot has yet.  Cleared once the enrollment succeeds
restore_crypttab=
# The same for the UKI mode, while `enroll` writes the entries for a new
# mode.  No slot has changed yet, so the slots still give the old mode
# (see `settle_uki_mode`)
restore_uki=

# Lifetime of the keys that sdbootutil adds to the kernel keyring.  The
# countdown starts again when the script exits.  So it measures how long
# a secret lives after the run that published it.  It never expires in
# the middle of a run
keyctl_timeout=600
created_keys=()

# Purposes already reported by `deprecated_keyring_secret`.  With
# several devices, the same warning is not repeated for each device
warned_keyring_secret=

declare -A eventlog

tmpdir=$(mktemp -d -t sdbootutil.XXXXXX)
cleanup()
{
	local i

	# Start again the countdown of the keys that this run created, so
	# that the run itself does not use it up.  Only the keys that we
	# created are touched.  An installer can leave an entry behind, and
	# a shorter lifetime can make it disappear while the installer
	# still needs it
	for i in "${created_keys[@]}"; do
		keyctl timeout "$i" "$keyctl_timeout" 2> /dev/null || \
			warn "Failed to set the timeout of the key $i"
	done

	for i in "${rollback[@]}"; do
		if [ -e "$i.bak" ]; then
			info "Restoring $i"
			mv "$i.bak" "$i"
		else
			info "Removing $i"
			rm -f "$i"
		fi
	done
	# A device can keep the option in /etc/crypttab but have no slot
	# for it.  During the boot it then falls back to the password
	# prompt, and this hides the failed enrollment.  The initrd embeds
	# /etc/crypttab, so the initrd has to be generated again.
	#
	# This is here and not in `enroll`, because every fatal path after
	# the options are added has to undo them.  There are several such
	# paths: `install_all_kernels`, `generate_tpm2_predictions` (when
	# the prediction cannot be signed), and a PIN that cannot be asked
	# because there is no terminal.  This runs after the rollback
	# above.  So the initrds are rebuilt from the restored file, and
	# the rollback does not undo them
	local rebuild=
	if [ -n "$restore_crypttab" ] && ! cmp -s "$tmpdir/crypttab" /etc/crypttab; then
		info "Restoring /etc/crypttab"
		cp -p "$tmpdir/crypttab" /etc/crypttab
		rebuild=1
	fi
	if [ -n "$restore_uki" ]; then
		info "Restoring the boot entries of the UKI mode in effect"
		settle_uki_mode
		rebuild=1
	fi
	# In a subshell because `err` calls `exit`.  Inside the trap, that
	# would skip the rest of this function, and $tmpdir would not be
	# removed
	if [ -n "$rebuild" ]; then
		# The addon of the root is written once per run.  The run
		# may have written it for the failed mode
		dps_addon_done=
		( install_all_kernels "$root_snapshot" ) || \
			warn "The boot entries still carry the failed enrollment"
	fi

	dbg "Cleaning temporary directory $tmpdir"
	rm -rf "$tmpdir"

	[ -z "$chroot_dir" ] || umount_chroot "$chroot_dir"
}
trap cleanup EXIT

entryfile="$tmpdir/entries.json"
initialentryfile="$tmpdir/initial_entries.json"
snapperfile="$tmpdir/snapper.json"
tmpfile="$tmpdir/tmp"
devicefile="$tmpdir/devices.json"

helpandquit()
{
	# Tabs are removed from the start of the line.  Use spaces to
	# indent
	cat <<-EOF
		Usage: $0 [OPTIONS] [COMMAND]
		OPTIONS:
		  --esp-path		Manually specify path to ESP
		  --arch		Manually set architecture
		  --entry-token		Override entry token
		  --image		Specify Linux kernel file name
		  --all			List all entries (inc. from other systems)
		  --entry-keys		Comma separated list of keys
		  --no-variables	Do not update UEFI variables
		  --no-reuse-initrd	Always regenerate initrd
		  --sync		Synchronize (update, downgrade) the bootloader
		  --portable		Handle bootloader on portable devices
		                        (also --removable possible)
		  --secure-boot		When installing the bootloader, use the shim
		  --only-default	Only list the default entry
		  --default-snapshot	[SNAPSHOT] refers to the default snapshot
		  --ask-key		Ask the new recovery key (or randomly generated)
		  --ask-pin		Ask the new TPM2 PIN, and the recovery PIN
		  --ask-recovery-pin	Ask only the recovery PIN
		  --ask-pw		Ask the new password
		  --ask-current-pw	Ask the password that already opens the devices
		  --method		"tpm2", "tpm2+pin", "fido2", "password", "recovery-key"
		  --no-measure-pcr	Do not bind the TPM2 slots to the initrd (PCR 15); they
		                        also unseal on the running system
		  --pcr			Comma seperated list of PCRs to enroll
		                        (the ones that cannot be predicted are dropped,
		                        unless --strict is used)
		  --devices		Comma separated list of devices to enroll or unenroll
		                        (by default all (not ignored) devices are [un]enrolled)
		  --rootfs		During bootloader installation, select the kind of 'root'
		                        valid selectors
		                        (uuid, partuuid, label, partlabel, device)
		  --rootfs-data		Extra data when --rootfs is used
		  --esp-free-space	Percentage of free space in the ESP
		  --devicetree-source	Absolute source path of a device tree blob to copy
		                        into the boot partition and reference from generated
		                        BLS entries. The source path is resolved in the
		                        target rootfs/snapshot. %K expands to the full
		                        kernel version and %V to the kernel package version
		                        without the flavor suffix. If configured, the
		                        resolved file must exist and be readable, and
		                        must be usable without Secure Boot, or kernel
		                        installation is aborted.
		  --force		Force certain operations inside a transaction,
		                        force the regeneration of the TPM2 policy, and
		                        accept in the TPM2 policy the files in the ESP
		                        that sdbootutil did not install, or that changed
		                        after it installed them
		  --strict		Every requested PCR must be part of the TPM2 policy,
		                        or nothing is applied (like systemd-pcrlock --strict=)
		  --disable-predictions	Disable automatic update predictions
		  --full		"status" reports every detail, not the summary
		  --repair		"cleanup" also writes back the kernels and initrds
		                        that boot entries name and the ESP does not have.
		                        The command line of the entry is left alone,
		                        "update-all-entries" is what rewrites those
		  -v, --verbose		More verbose output
		  --start-trace-code	Create /var/log/sdbootutil.log to trace the code.
		                        (verbose output is enabled)
		  --stop-trace-code	Remove /var/log/sdbootutil.log to stop tracing the code
		  -h, --help		This screen
		  --version		Print the version and exit

		COMMAND:
		bootloader [SNAPSHOT]
		           Print the detected bootloader

		add-kernel VERSION [SNAPSHOT]
		           Create boot entry for specified kernel

		add-all-kernels [SNAPSHOT]
		           Create boot entries for all kernels in SNAPSHOT

		mkinitrd [SNAPSHOT]
		           Create boot entries for all kernels in SNAPSHOT,
		           assumes --no-reuse-initrd to regenerate initrds

		remove-kernel VERSION [SNAPSHOT]
		           Remove boot entry for specified kernel

		remove-all-kernels [SNAPSHOT]
		           Remove boot entries for all kernels in SNAPSHOT

		cleanup [SNAPSHOT]
		           Remove boot entries with missing kernels from SNAPSHOT.
		           With --repair, also install again the kernels and initrds
		           that the remaining entries name and the ESP does not have.
		           Only those files are written, what the entry says is kept

		list-kernels [SNAPSHOT]
		           List all kernels related to SNAPSHOT

		list-entries [SNAPSHOT]
		           List all entries related to SNAPSHOT.  On a
		           terminal the entry is marked with "+" when it
		           is the default one, "-" when the system booted
		           from it, and "*" when it is both

		list-snapshots
		           List all snapshots.  On a terminal the snapshot
		           is marked with "+" when it is the default one,
		           "-" when the system is running from it, and "*"
		           when it is both

		list-devices
		           List encrypted devices that are tracked

		status
		           Report what the machine boots and whether the TPM2
		           will open it.  Only reads, and prints no secret, so
		           it is safe to attach to a bug report.  --full for
		           every detail instead of the summary

		show-entry VERSION [SNAPSHOT]
		           Show fields for an entry with an specified kernel
		           version

		update-entry VERSION [SNAPSHOT]
		           Update "options" field from /etc/kernel/cmdline
		           for an entry, or the addon of a UKI

		update-all-entries [SNAPSHOT]
		           Update "options" field from /etc/kernel/cmdline
		           for all entries, and the addons of the UKIs

		set-default-snapshot [SNAPSHOT]
		           Make SNAPSHOT the default for next boot.
		           Also install all kernels if needed

		is-bootable [SNAPSHOT]
		           Check whether SNAPSHOT has any kernels registered, ie
		           is potentially bootable

		install
		           Install the bootloader and shim into ESP

		needs-update
		           Check whether the bootloader or the shim in ESP needs
		           updating

		update
		           Update the bootloader and the shim in the ESP if a
		           newer version is available. Passing the --sync option
		           will also allow downgrades, ensuring that the version
		           in the ESP matches the one installed in the system.

		force-update
		           Update the bootloader in any case

		set-default ID
		           Set default boot loader entry

		get-default
		           Get default boot loader entry

		set-timeout SECONDS|menu-disabled|menu-hidden|menu-force
		           Set the menu timeout
		           menu-disabled or menu-hidden=0; menu-force=-1

		get-timeout
		           Get the menu timeout in seconds

		print-loader-path
		           Print path to currently booted boot loader binary

		enroll
		           Enroll a TPM2 (+PIN), a FIDO2 key or a password for
		           all devices

		unenroll
		           Unenroll a TPM2 (+PIN), a FIDO2 key or a password for
		           all devices

		update-predictions
		           Update TPM2 predictions

		sync-pcrlock-policy
		           Publish a policy made by the systemd-pcrlock service
		           (called by it, for fwupd)

		Secrets:
		Each one is taken from the --ask-X parameter, the X variable
		or the %u:sdbootutil-x keyring entry, in that order.

		Presented, to authorize a change:

		                  parameter          variable      keyring (%u)
		Current password  --ask-current-pw   CURRENT_PW    cryptenroll
		Recovery PIN      --ask-recovery-pin RECOVERY_PIN  sdbootutil-recovery-pin

		Enrolled, as the new secret:

		Recovery key      --ask-key          KEY           sdbootutil-key
		Password          --ask-pw           PW            sdbootutil-pw
		TPM2 PIN          --ask-pin          PIN           sdbootutil-tpm2-pin

		The TPM2 PIN is typed at every boot; the recovery PIN
		re-authorizes the pcrlock NVIndex, and PIN also names it when
		there is no TPM2 PIN (--method=tpm2, update-predictions).
		--ask-pin asks both.

		The recovery PIN cannot be changed: the same value has to
		authorize the old NVIndex and seal the new one.  It is sealed
		by the first enrollment, taken from the recovery key so that
		there is a single secret to keep, and only presented after
		that.  With no source both are generated and printed.

		Prefer the keyring, it expires and the environment does not.
		%u:sdbootutil (any secret, read last) and %u:sdbootutil-pin
		(now -recovery-pin) are deprecated.

		Variables:
		SYSTEMD_COLORS	Set 0 to disable colored output
		CURRENT_PW, KEY, PW, PIN and RECOVERY_PIN are in Secrets:

		Misc:
		Ignoring Devices	A LUKS2 device can be un-tracked (ignored)
		                        by sdbootutil if is present in /etc/crypttab
		                        and has the "x-sdbootutil.ignore" option
		Trace Code		Create /var/log/sdbootutil.log to debug deep
		                        sdbootutil calls.  Remove the file to stop the
		                        trace, and audit the content before sharing
		Applied Snapshots	After a "transactional-update apply" the running
		                        system is a mix of two snapshots.  [SNAPSHOT] has
		                        no meaningful default then, so commands that
		                        change the ESP require an explicit snapshot
		                        number or --default-snapshot


	EOF
	exit 0
}

dbg()
{
	[ "${verbose:-0}" -gt 1 ] || return 0
	echo -e "DEBUG: $*" >&2
}

dbg_var()
{
	[ "${verbose:-0}" -gt 1 ] || return 0
	local v="${1:?}"
	echo "DEBUG: $v: ${!v}" >&2
}

dbg_cat()
{
	[ "${verbose:-0}" -gt 1 ] || return 0
	[ ! -e "$1" ] || { echo "DEBUG: $1" >&2; cat "$1" >&2; }
}

info()
{
	[ "${verbose:-0}" -gt 0 ] || return 0
	echo -e "$@" >&2
}

warn()
{
	echo -e "WARNING: $*" >&2
}

err()
{
	echo -e "ERROR: $*" >&2
	exit 1
}

is_config_file()
{
	[ -e /usr/etc/default/sdbootutil ] ||
		[ -e /etc/default/sdbootutil ] ||
		[ -e /usr/etc/default/fde-tools ] ||
		[ -e /etc/default/fde-tools ] ||
		[ -e /etc/sysconfig/fde-tools ]
}

set_default_config_values()
{
	FDE_SEAL_PCR_LIST="$arg_pcr"
	if is_installed && [ -z "${FDE_SEAL_PCR_LIST}" ]; then
		if systemd-detect-virt -q; then
			info "Virtualized systemd detected ($(systemd-detect-virt)). Dropping PCR0 and PCR2"
			FDE_SEAL_PCR_LIST=""
		else
			FDE_SEAL_PCR_LIST="0,2,"
		fi
		if is_sdboot; then
			FDE_SEAL_PCR_LIST+="4,7,9"
		elif is_grub2_bls; then
			FDE_SEAL_PCR_LIST+="4,7,8,9"
		else
			err "Bootloader not detected"
		fi
	fi

	if is_rootfs_crypt; then
		# PCR 15 in the TPM2 policy protects from impostor
		# LUKS2 volumes, as it measures the volume key.  But a
		# non-encrypted device (USB, for example) can have a
		# volume with the same metadata as the internal volume
		# in the encrypted root device.  /etc/fstab refers to
		# that metadata.  So there is a chance that this
		# volume gets mounted in /sysroot.  systemd can
		# measure data of the file system (like the UUID or
		# /etc/machine-id) with systemd-validatefs@.service.
		# But this data is public and can be copied
		#
		# See bsc#1229934 for more details
		ROOTFS="device"
	else
		ROOTFS="uuid"
	fi
	ROOTFS="${arg_rootfs:-$ROOTFS}"

	ESP_FREE_SPACE="${arg_esp_free_space:-10}"
	DEVICETREE_SOURCE="${arg_devicetree_source:-}"
	UKI_CMDLINE="yes"
}

create_default_config_file()
{
	! is_config_file || return 0

	set_default_config_values
	cat <<-EOF > /etc/default/sdbootutil
	# Default sdbootutil configuration file generated automatically

	# List of PCRs.  For VMs PCRs 0 and 2 are dropped
	FDE_SEAL_PCR_LIST="$FDE_SEAL_PCR_LIST"

	# Parameter used in the cmdline to find the root (device, [part]uuid, [part]label)
	# For encrypted devices it is forced "device"
	ROOTFS="$ROOTFS"

	# Percentage (%) of free space in the ESP that sdbootutil should guarantee
	# Default values is 10%
	ESP_FREE_SPACE="$ESP_FREE_SPACE"

	# Optional absolute path to a device tree blob. If set, it is copied to the
	# boot partition and a devicetree field is added to generated BLS entries.
	# The source path is resolved in the target rootfs/snapshot. %K expands to
	# the full kernel version, %V to the kernel package version without the
	# flavor suffix. If set, the resolved file must exist and be readable,
	# otherwise kernel installation aborts. Currently supported only with
	# Secure Boot disabled.
	DEVICETREE_SOURCE="$DEVICETREE_SOURCE"

	# "yes" adds the kernel command line of the system (/etc/kernel/cmdline
	# and cmdline.d) to the UKIs, in the addon of each boot entry
	UKI_CMDLINE="$UKI_CMDLINE"
	EOF
}

load_config_file()
{
	local f

	set_default_config_values

	# Prioritize sdbootutil configuration file, and use fde-tools
	# as a fallback
	for f in /usr/etc/default/sdbootutil \
			 /etc/default/sdbootutil \
			 /usr/etc/default/fde-tools \
			 /etc/default/fde-tools \
			 /etc/sysconfig/fde-tools; do
		[ ! -e "$f" ] || {
			# shellcheck disable=SC1090
			. "$f"
			info "Loading config file $f"
			dbg_cat "$f"
		}
	done

	# Force back "device" for ROOTFS if the root is encrypted.  This
	# is not a user error.  The config file is generated before
	# disk-encryption-tool encrypts the root on first boot, so it
	# keeps "uuid".  `status` already reports the value as forced
	if is_rootfs_crypt; then
		[ "$ROOTFS" = "device" ] || dbg "ROOTFS=$ROOTFS in the config file, forcing 'device' as the root is encrypted"
		ROOTFS="device"
	fi

	# If arguments are passed, use them
	FDE_SEAL_PCR_LIST="${arg_pcr:-$FDE_SEAL_PCR_LIST}"
	ROOTFS="${arg_rootfs:-$ROOTFS}"
	ESP_FREE_SPACE="${arg_esp_free_space:-$ESP_FREE_SPACE}"
	DEVICETREE_SOURCE="${arg_devicetree_source:-$DEVICETREE_SOURCE}"
}

is_secure_boot()
{
	grep -q $'\x01' /sys/firmware/efi/efivars/SecureBoot-8be4df61-93ca-11d2-aa0d-00e098032b8c 2> /dev/null
}

bootloader_type()
{
	# If LOADER_TYPE is set, use that
	if [ -n "$LOADER_TYPE" ]; then
		echo "$LOADER_TYPE"
		return
	fi

	local sdboot grub2_bls

	sdboot="$(find_sdboot "${1-$root_snapshot}")"
	grub2_bls="$(find_grub2_bls "${1-$root_snapshot}")"

	# If LOADER_TYPE is unset and only systemd-boot is installed, use that
	if [ -e "$sdboot" ] && ! [ -e "$grub2_bls" ]; then
		echo "systemd-boot"
		return
	fi

	# Otherwise, use grub2-bls
	echo "grub2-bls"
}

is_sdboot()
{
	[ "$(bootloader_type "${1-$root_snapshot}")" = "systemd-boot" ]
}

is_grub2_bls()
{
	[ "$(bootloader_type "${1-$root_snapshot}")" = "grub2-bls" ]
}

# UKI, from /etc/sysconfig/bootloader, selects the kind of boot entry.
# "no", empty or unset is a Type #1 entry (kernel and initrd).  "yes" is
# the UKI of the kernel package, signed by the distribution.  "local" is
# a UKI built here, signed with the local key when SECURE_BOOT is "yes".
# Only systemd-boot boots the UKIs.  It loads the addons of an entry,
# and the snapshot is in an addon.  With another boot loader the entries
# use the kernel and the initrd
assert_uki_config()
{
	case "${UKI:-}" in
		""|no) return 0 ;;
		yes|local) ;;
		*) err "/etc/sysconfig/bootloader has UKI=\"$UKI\", but only \"yes\", \"no\" or \"local\" are recognized" ;;
	esac
	is_sdboot || {
		warn "UKI=\"$UKI\" in /etc/sysconfig/bootloader needs systemd-boot, using the kernel and the initrd"
		UKI=""
		return 0
	}

	# The tools of the UKIs are checked once, here.  With UKI="yes"
	# only the addon of the snapshot is built and signed
	local tool missing=()
	for tool in openssl systemd-creds objcopy objdump "$systemd_sbsign" \
		    $([ "$UKI" = "local" ] && echo "$systemd_measure") $(is_shim_installed && echo mokutil); do
		command -v "$tool" > /dev/null || missing+=("${tool##*/}")
	done
	[ "${#missing[@]}" -eq 0 ] || err "UKI=\"$UKI\" needs ${missing[*]}"
}

# The UKI of /etc/sysconfig/bootloader.  After `settle_uki_mode`, UKI
# is the mode in effect
uki_config=

# The TPM2 slots decide the mode in effect.  A slot made for the UKIs
# (signed PCR 11) never opens a kernel and an initrd.  So the UKI of the
# configuration takes effect only with "enroll", that replaces the
# slots.  A signed slot with the key of this system is for UKI="local".
# A signed slot with another key is for UKI="yes".  A slot bound to PCR
# 15 without a signature is for the kernel and the initrd.  The other
# slots work with both modes, so they do not decide.  An example is the
# pcrlock slot of a device that the initrd does not open
settle_uki_mode()
{
	uki_config="${UKI:-}"
	grep -qs "^[^#]*tpm2-device" /etc/crypttab || return 0
	# All the devices, not only the ones given with --devices
	local tracked_devices=()
	detect_tracked_devices || return 0

	local key="" dev slot
	[ ! -e "$pcr_public_key" ] || key="$(base64 -w0 < "$pcr_public_key")"
	for dev in "${tracked_devices[@]}"; do
		slot="$(luks_header "$dev" | jq -r --arg key "$key" "$jq_tpm2_token_defs"'[.tokens[]? | select(pcrlock)]
			| if any(signed) then (if any(.tpm2_pubkey == $key) then "local" else "yes" end)
			  elif any(bound) then "plain" else empty end')"
		# A signed slot is enough to decide
		case "$slot" in
			local|yes) UKI="$slot"; break ;;
			plain) UKI="" ;;
		esac
	done
	[ "$UKI" = "$uki_config" ] || dbg "UKI=\"$uki_config\" takes effect when the TPM2 is enrolled again ('sdbootutil enroll --method tpm2'), the TPM2 slots are for UKI=\"$UKI\""
}

# The UKIs are selected in /etc/sysconfig/bootloader
uki_selected()
{
	[ "${UKI:-}" = "local" ] || [ "${UKI:-}" = "yes" ]
}

# Check if the system follows the Discoverable Partitions Specification
# (DPS), and if not, print why.  The UKIs of the distribution have no
# "root=", so they need DPS.  udev names the partitions of the boot disk
# the same way as the discovery does (90-image-dissect.rules).  udev
# names a LUKS2 root only when it is opened as "root".  A btrfs over
# several devices is found, but its other devices are not opened
dps_root_problem()
{
	local dev fstype
	read -r dev fstype < <(findmnt -n -v -o SOURCE,FSTYPE /)
	if [ "$fstype" = "btrfs" ] && [ "$(btrfs filesystem show --raw / 2> /dev/null | grep -c devid)" -gt 1 ]; then
		echo "the root file system is on more than one device"
	elif ! is_same_device /dev/disk/by-designator/root "$dev"; then
		if [ -e /dev/disk/by-designator/root-luks ]; then
			echo "the encrypted root is not opened as \"root\""
		else
			echo "the root file system is not on a partition that the discovery finds"
		fi
	fi
}

# The value of UKI, in words
uki_mode_text()
{
	case "${UKI:-}" in
		yes) echo "yes, the UKIs of the distribution" ;;
		local) echo "local, built and signed in this system" ;;
		*) echo "no, kernel and initrd" ;;
	esac
}

# UKI_CMDLINE, in words.  With "no", it lists the options of the kernel
# command line that the UKIs do not have.  They are listed one by one.
# This is because the order, and the values that override others,
# cannot be known here
uki_cmdline_text()
{
	[ "$UKI_CMDLINE" = "no" ] || {
		echo "yes, in the addon of each entry"
		return 0
	}
	local known=" ro " uki f param lost=()
	if [ "$UKI" = "yes" ]; then
		known=" "
		uki="$(compgen -G "/usr/lib/modules/$(uname -r)/vmlinuz-*.efi" | head -n 1)"
		for f in ${uki:+"$uki" "$uki".extra.d/*.addon.efi}; do
			[ -e "$f" ] || continue
			objcopy -O binary --only-section=.cmdline "$f" "$tmpdir/uki-cmdline" 2> /dev/null || continue
			known+="$(< "$tmpdir/uki-cmdline") "
		done
		rm -f "$tmpdir/uki-cmdline"
	fi
	while read -r param; do
		[[ "$param" == root=* ]] || [[ "$param" == rootflags=* ]] || [[ "$known" == *" $param "* ]] || lost+=("$param")
	done < <(cmdline_params "$(kernel_cmdline "")")
	echo "no${lost[*]:+, not used: ${lost[*]}}"
}

# With UKI="yes" each kernel needs its UKI from the distribution, in
# /usr/lib/modules/<version>/vmlinuz-<variant>.efi.  sdbootutil cannot
# install the package, so it prints the kernels that have no UKI.  The
# dash matters: vmlinuz.efi is a kernel (arm64 zboot), not a UKI
uki_missing_kernels()
{
	[ "${UKI:-}" = "yes" ] || return 0
	local modules="${1:-/usr/lib/modules}" image dir
	for image in "$modules"/*/vmlinuz; do
		[ -e "$image" ] || continue
		dir="${image%/vmlinuz}"
		compgen -G "$dir/vmlinuz-*.efi" > /dev/null || echo "${dir##*/}"
	done
}

# The keys of UKI="local".
# The private keys are only stored encrypted by systemd-creds, with the
# TPM2 and the host key.  They are never written in clear.  They live in
# a variable and pass through pipes.
#  - The Secure Boot key signs the UKIs and the addons.  It is enrolled
#    with mokutil.  It is RSA 4096, like the keys of OBS
#  - The PCR key signs the PCR 11 policy of the initrd, only with FDE.
#    The TPM2 loads it.  So it is RSA 4096 only if the TPM2 supports it,
#    else RSA 2048
secureboot_certificate=/etc/kernel/secureboot-certificate.pem
# ukify uses this name for a key that signs only the enter-initrd phase.
# The name is not tpm2-pcr-public-key.pem: in /etc, that file would hide
# the key of the distribution (UKI="yes") from every systemd tool
pcr_public_key=/etc/systemd/tpm2-pcr-initrd-public-key.pem
credstore=/etc/credstore.encrypted

# Print the private key NAME, decrypted, for a pipe or a process
# substitution: --private-key=<(private_key NAME)
private_key()
{
	systemd-creds decrypt --name="$1" "$credstore/$1" -
}

# Pass the private key NAME to "openssl CMD..." on stdin, to write the
# public part.  A missing key is made with BITS bits, and stored
# encrypted
public_part()
{
	local -; set +x
	local name="$1" bits="$2" key
	shift 2
	if [ -e "$credstore/$name" ]; then
		key="$(private_key "$name")" || err "Cannot read the key $name"
	else
		key="$(openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:"$bits" 2> /dev/null)" || \
			err "Cannot make the key $name"
		mkdir -p "$credstore"
		chmod 700 "$credstore"
		echo "$key" | systemd-creds encrypt --with-key=tpm2+host --name="$name" - "$credstore/$name" || \
			err "Cannot encrypt the key $name"
	fi
	echo "$key" | openssl "$@" || err "Cannot write the public part of $name"
}

# Make the keys that are missing, or their public part
uki_keys()
{
	uki_selected || return 0

	if [ ! -e "$credstore/secureboot-private-key.pem" ] || [ ! -e "$secureboot_certificate" ]; then
		info "Making the Secure Boot key that signs the UKIs"
		mkdir -p "${secureboot_certificate%/*}"
		public_part secureboot-private-key.pem 4096 \
			req -new -x509 -key /dev/stdin -days 3650 \
			-subj "/CN=SecureBoot signing key on host $(uname -n)" \
			-addext "extendedKeyUsage=codeSigning" \
			-out "$secureboot_certificate"
	fi

	# The UKIs of the distribution are signed by the distribution
	[ "$UKI" = "local" ] || return 0
	grep -qs "^[^#]*tpm2-device" /etc/crypttab || return 0
	if [ ! -e "$credstore/tpm2-pcr-initrd-private-key.pem" ] || [ ! -e "$pcr_public_key" ]; then
		info "Making the key that signs the PCR 11 policy"
		local bits=2048
		! tpm2_testparms rsa4096 &> /dev/null || bits=4096
		mkdir -p "${pcr_public_key%/*}"
		public_part tpm2-pcr-initrd-private-key.pem "$bits" \
			pkey -pubout -out "$pcr_public_key"
	fi
}

# The public key of the signed PCR 11 policy of the UKIs, for the TPM2
# slot.  With UKI="local" it is our own key.  With UKI="yes" it is the
# key of the package, or else the key inside the UKI of the running
# kernel
uki_pcr_public_key()
{
	local uki
	if [ "$UKI" = "local" ]; then
		[ -e "$pcr_public_key" ] && echo "$pcr_public_key"
		return
	fi
	if [ -e /usr/lib/systemd/tpm2-pcr-public-key.pem ]; then
		echo /usr/lib/systemd/tpm2-pcr-public-key.pem
		return 0
	fi
	for uki in /usr/lib/modules/"$(uname -r)"/vmlinuz-*.efi; do
		[ -e "$uki" ] || continue
		objcopy -O binary --only-section=.pcrpkey "$uki" "$tmpdir/pcrpkey.pem" 2> /dev/null || continue
		[ -s "$tmpdir/pcrpkey.pem" ] || continue
		echo "$tmpdir/pcrpkey.pem"
		return 0
	done
	return 1
}

systemd_sbsign=/usr/lib/systemd/systemd-sbsign
systemd_measure=/usr/lib/systemd/systemd-measure

# Copy the PE file IN to OUT, adding the sections NAME FILE...  Each
# section starts after the last one, aligned like the others
pe_add_sections()
{
	local in="$1" out="$2" idx name size vma align next args=()
	shift 2
	# The lines of the sections start with their index
	while read -r idx name size vma _; do
		[[ "$idx" =~ ^[0-9]+$ ]] && next=$((0x$vma + 0x$size))
	done < <(objdump -h "$in")
	while read -r name align; do
		[ "$name" = "SectionAlignment" ] && break
	done < <(objdump -p "$in")
	while [ $# -gt 0 ]; do
		next=$(((next + 0x$align - 1) / 0x$align * 0x$align))
		args+=(--add-section "$1=$2" --change-section-vma "$1=$(printf '0x%x' "$next")")
		next=$((next + $(stat -L -c %s "$2")))
		shift 2
	done
	objcopy "${args[@]}" "$in" "$out"
}

# The time written in the UKIs and the addons is the start date of the
# certificate.  So a file built again with the same content is the same
# file, and its measurement does not change.  objcopy (for the time of
# the PE header) and systemd-sbsign (for the signing time) read it from
# SOURCE_DATE_EPOCH
signing_epoch()
{
	date -d "$(openssl x509 -in "$secureboot_certificate" -noout -startdate | cut -d= -f2)" +%s
}

# A signed addon in OUT, that adds CMDLINE to the kernel command line,
# and the initrd INITRD if there is one.  The addon has no .uname, so
# it works with any kernel
build_addon()
{
	local cmdline="$1" out="$2" initrd="${3:-}"
	local -x SOURCE_DATE_EPOCH
	SOURCE_DATE_EPOCH="$(signing_epoch)"
	echo -n "$cmdline" > "$tmpdir/addon.cmdline"
	cat > "$tmpdir/addon.sbat" <<-EOF
	sbat,1,SBAT Version,sbat,1,https://github.com/rhboot/shim/blob/main/SBAT.md
	uki-addon,1,UKI Addon,addon,1,https://www.freedesktop.org/software/systemd/man/latest/systemd-stub.html
	EOF
	pe_add_sections "/usr/lib/systemd/boot/efi/addon$firmware_arch.efi.stub" "$tmpdir/addon.efi" \
		${cmdline:+.cmdline "$tmpdir/addon.cmdline"} \
		.sbat "$tmpdir/addon.sbat" \
		${initrd:+.initrd "$initrd"}
	SYSTEMD_LOG_LEVEL=warning "$systemd_sbsign" sign --private-key=<(private_key secureboot-private-key.pem) \
		--certificate="$secureboot_certificate" --output="$out" "$tmpdir/addon.efi" || \
		err "Cannot sign the addon"
	rm -f "$tmpdir/addon.cmdline" "$tmpdir/addon.sbat" "$tmpdir/addon.efi"
}

# The lines of /etc/crypttab that dracut puts in a host-only initrd.
# These are the lines with "x-initrd.attach" or "force", and the devices
# that the system needs (root, resume...).  `dracut --print-cmdline`
# names those devices in "rd.luks.uuid=".  This is for the initrd of a
# UKI, that knows nothing of the disks (see `update_dps_addon`)
dracut_crypttab()
{
	local param uuids="" line name device _ opts uuid
	[ -e /etc/crypttab ] || return 0
	while IFS= read -r line || [ -n "$line" ]; do
		read -r name device _ opts <<<"$line"
		[ -n "$name" ] && [[ "$name" != \#* ]] || continue
		if [[ ",$opts," != *",x-initrd.attach,"* ]] && [[ ",$opts," != *",force,"* ]]; then
			# dracut takes seconds to answer, so it is asked only
			# here, once
			if [ -z "$uuids" ]; then
				uuids=" "
				while read -r param; do
					[[ "$param" == rd.luks.uuid=* ]] || continue
					param="${param#rd.luks.uuid=}"
					uuids+="${param#luks-} "
				done < <(cmdline_params "$(dracut --print-cmdline 2> /dev/null)")
			fi
			case "$device" in
				UUID=*) uuid="${device#UUID=}" ;;
				*) uuid="$(cryptsetup luksUUID "$(device_path "$device")" 2> /dev/null)" ;;
			esac
			[ -n "$uuid" ] && [[ "$uuids" == *" $uuid "* ]] || continue
		fi
		echo "$line"
	done < /etc/crypttab
}

# The lines of `dracut_crypttab` for the addon of the root.  With DPS
# (DPS is not empty), the discovery opens the root and /usr by itself,
# as "root" and "usr".  So their lines are left out
addon_crypttab()
{
	local dps="$1" line name
	while IFS= read -r line; do
		read -r name _ <<<"$line"
		if [ -n "$dps" ] && { [ "$name" = "root" ] || [ "$name" = "usr" ]; }; then
			continue
		fi
		echo "$line"
	done < <(dracut_crypttab)
}

# A cpio archive in OUT with a crypttab with the lines LINES.  The same
# lines give the same bytes.  So the addon that carries the archive is
# only written again when the lines change
crypttab_cpio()
{
	local out="${1:?}" lines="$2" dir="$tmpdir/crypttab-cpio"
	rm -rf "$dir"
	mkdir -p "$dir/etc"
	: > "$dir/etc/crypttab"
	[ -z "$lines" ] || echo "$lines" > "$dir/etc/crypttab"
	chmod 755 "$dir" "$dir/etc"
	chmod 644 "$dir/etc/crypttab"
	touch -h -d @0 "$dir/etc/crypttab" "$dir/etc" "$dir"
	(cd "$dir" && find . | LC_ALL=C sort | cpio --quiet -o -H newc --reproducible -R 0:0) > "$out"
	rm -rf "$dir"
}

# A signed UKI in OUT, from the kernel LINUX, the initrd INITRD, the
# kernel command line CMDLINE, the os-release file OSREL and the kernel
# version UNAME.  With FDE it also carries the signed PCR 11 policy of
# the initrd.  The TPM2 slots of the UKIs need this policy
build_uki()
{
	local linux="$1" initrd="$2" cmdline="$3" osrel="$4" uname="$5" out="$6"
	local -x SOURCE_DATE_EPOCH
	SOURCE_DATE_EPOCH="$(signing_epoch)"
	local stub="/usr/lib/systemd/boot/efi/linux$firmware_arch.efi.stub"
	echo -n "$cmdline" > "$tmpdir/uki.cmdline"
	echo -n "$uname" > "$tmpdir/uki.uname"
	local sections=(.osrel "$osrel" .cmdline "$tmpdir/uki.cmdline" .uname "$tmpdir/uki.uname")

	# The signature is made from the files that go in the UKI,
	# including the .sbat of the stub.  Each byte of them is measured
	if [ -e "$credstore/tpm2-pcr-initrd-private-key.pem" ]; then
		objcopy -O binary --only-section=.sbat "$stub" "$tmpdir/uki.sbat"
		SYSTEMD_LOG_LEVEL=warning "$systemd_measure" sign \
			--linux="$linux" --initrd="$initrd" --cmdline="$tmpdir/uki.cmdline" \
			--osrel="$osrel" --uname="$tmpdir/uki.uname" --sbat="$tmpdir/uki.sbat" \
			--pcrpkey="$pcr_public_key" --bank=sha256 \
			--phase=enter-initrd --policyref=initrd \
			--private-key=<(private_key tpm2-pcr-initrd-private-key.pem) \
			--public-key="$pcr_public_key" --json=short > "$tmpdir/uki.pcrsig" || \
			err "Cannot sign the PCR 11 policy of the UKI"
		sections+=(.pcrpkey "$pcr_public_key" .pcrsig "$tmpdir/uki.pcrsig")
	fi

	sections+=(.initrd "$initrd" .linux "$linux")
	pe_add_sections "$stub" "$tmpdir/uki.efi" "${sections[@]}"
	SYSTEMD_LOG_LEVEL=warning "$systemd_sbsign" sign --private-key=<(private_key secureboot-private-key.pem) \
		--certificate="$secureboot_certificate" --output="$out" "$tmpdir/uki.efi" || \
		err "Cannot sign the UKI"
	rm -f "$tmpdir"/uki.{cmdline,uname,sbat,pcrsig,efi}
}

# The Secure Boot certificate in MOK: "enrolled", "pending" (waits for
# MokManager at the next boot) or "missing"
mok_state()
{
	local der="$tmpdir/secureboot-certificate.der"
	openssl x509 -in "$secureboot_certificate" -outform DER -out "$der" 2> /dev/null || {
		echo "missing"
		return 0
	}
	case "$(mokutil --test-key "$der" 2> /dev/null)" in
		*"already enrolled"*) echo "enrolled" ;;
		*"enrollment request"*) echo "pending" ;;
		*) echo "missing" ;;
	esac
}

# With Secure Boot, systemd-boot starts the UKIs, and shim verifies them
# with the certificates in MOK.  So a missing certificate is imported.
# The user confirms it in MokManager at the next boot.  The password is
# the root password.  When root has no password, or one that MokManager
# cannot check, a one-time password is used.  If that boot did not
# enroll it (skipped, wrong password), the next run imports it again
mok_enroll()
{
	local -; set +x
	is_secure_boot || return 0
	[ -e "$secureboot_certificate" ] || return 0
	is_shim_installed || {
		warn "Secure Boot without shim: the UKIs signed here cannot boot, as only shim reads MOK"
		return 0
	}

	# `mok_state` also writes the DER certificate that the import
	# below reads
	local marker=/var/lib/sdbootutil/mok-import
	case "$(mok_state)" in
		enrolled)
			rm -f "$marker"
			return 0
			;;
		pending)
			warn "The UKI certificate waits to be enrolled in MOK at the next boot"
			return 0
			;;
	esac

	[ ! -e "$marker" ] || warn "The UKI certificate was not enrolled in MOK at the last boot, importing it again"

	local password="" which="the root password"
	case "$(getent shadow root | cut -d: -f2)" in
		\$1\$*|\$5\$*|\$6\$*|\$2[aby]\$*)
			mokutil --import "$tmpdir/secureboot-certificate.der" --root-pw || \
				err "Cannot import the UKI certificate in MOK"
			;;
		*)
			which="the password shown below"
			password="$(tr -dc 0-9 < /dev/urandom | head -c 8)"
			mokutil --import "$tmpdir/secureboot-certificate.der" \
				--hash-file <(mokutil --generate-hash="$password") || \
				err "Cannot import the UKI certificate in MOK"
			;;
	esac
	touch "$marker"

	warn "The UKIs are signed with a new key.  At the next boot, MokManager asks to enroll it:"
	warn "  1. Press a key, and select \"Enroll MOK\", \"Continue\" and \"Yes\""
	warn "  2. Type $which (MokManager uses a US keyboard)"
	warn "  3. Select \"Reboot\""
	warn "Until then, the system boots the kernel and initrd entries"
	[ -z "$password" ] || echo "MOK password: $password"
}

reset_rollback()
{
	for i in "${rollback[@]}"; do
		[ -e "$i.bak" ] || continue
		info "Removing $i.bak"
		rm -f "$i.bak"
	done
	rollback=()
}

is_transactional()
{
	findmnt --fstab / -O ro &> /dev/null
}

# %user:sdbootutil is a single entry.  It is read as a different secret
# for each method: the new recovery key, the new password, the TPM2 PIN,
# or the recovery PIN of the pcrlock NVIndex.  So a value left there for
# one purpose is used for another one.  Now each purpose has its own
# entry.  This old entry is still read, last, only for the installers
# that have not moved yet
deprecated_keyring_secret()
{
	local purpose="${1:?}"
	local name="${2:?}"
	local old="${3:-sdbootutil}"

	[[ "$warned_keyring_secret" != *"|$old>$name|"* ]] || return 0
	warned_keyring_secret+="|$old>$name|"
	warn "Reading the $purpose from %user:$old is deprecated. Use %user:$name"
}

# The recovery PIN used to live in %user:sdbootutil-pin.  That name is
# one character away from %user:sdbootutil-tpm2-pin, that holds the PIN
# typed at every boot.  They are different secrets: the recovery PIN
# rewrites the pcrlock policy.  So the old name is deprecated, but it is
# still read
recovery_pin_keyid()
{
	local keyid

	if keyid="$(keyctl id %user:sdbootutil-recovery-pin 2> /dev/null)"; then
		echo "$keyid"
	elif keyid="$(keyctl id %user:sdbootutil-pin 2> /dev/null)"; then
		deprecated_keyring_secret "recovery PIN" "sdbootutil-recovery-pin" "sdbootutil-pin"
		echo "$keyid"
	else
		return 1
	fi
}

# Secrets and --start-trace-code
#
# The trace records every command after its expansion.  So a secret
# that reaches a traced line ends in /var/log/sdbootutil.log, and users
# attach that file to bug reports.  Two rules keep the secrets out:
#
# - A function that needs the value of a secret starts with
#   `local -; set +x`.  `local -` makes the shell options local to the
#   function.  So the trace comes back when the function returns, also
#   on error.  The function reaches the secrets of the caller by name
#   (`local -n`).  So its own locals have a prefix, as a local with the
#   same name would hide the secret of the caller
# - Everywhere else a secret is only named.  It is passed as the name
#   of the variable that holds it.  It is tested with "${var:+set}",
#   that expands to "set" and never to the value

# Run "$@" with the secret in the variable named $2 exported as $1.
# The traced call shows the whole command, with the name of the
# variable in place of the value
run_with_secret()
{
	local -; set +x
	local -n rws_secret="$2"
	local -x "$1=$rws_secret"
	shift 2
	"$@"
}

# Store the secret in the variable named $2 as %user:$1
keyctl_add_with_timeout()
{
	local -; set +x
	local kawt_name="$1"
	local -n kawt_value="$2"

	# Installers do not agree on the keyring.  yast-bootloader,
	# disk-encryption-tool and jeos-firstboot use @u, but
	# yast-storage-ng uses @s.  `keyctl padd` only updates an entry
	# that is already in the *target* keyring.  `keyctl link` replaces
	# (and destroys) an entry with the same name in the destination.
	# So any fixed keyring damages one of them.  `keyctl pupdate`
	# rewrites the payload where the entry already lives
	local kawt_keyid
	if kawt_keyid="$(keyctl id %user:"$kawt_name" 2> /dev/null)"; then
		info "Updating key $kawt_name"
		echo -n "$kawt_value" | keyctl pupdate "$kawt_keyid" || \
			warn "Failed to update the key $kawt_name"
		# The entry belongs to somebody else, so neither its
		# permissions nor its lifetime are changed here
		return 0
	fi

	info "Creating key $kawt_name with timeout"
	# When we create a new key with sudo, no new login session is
	# created, so the key is not accessible to the owner.
	# See https://mjg59.dreamwidth.org/37333.html
	kawt_keyid="$(echo -n "$kawt_value" | keyctl padd user "$kawt_name" @u)"
	# Remove the permissions of the possessor.  For some reason that I
	# do not understand, this can fail in YaST when called via cheetah.
	# Returning here would leave the secret in the keyring with no
	# expiry at all.  That is worse than the wrong permissions
	keyctl setperm "$kawt_keyid" 0x003f0000 2> /dev/null || \
		warn "Failed to change the permissions of $kawt_name"
	# The countdown starts here only as a backstop, for a run that is
	# killed before `cleanup` can start it again.  Every consumer comes
	# after a slow step (dracut, `systemd-pcrlock make-policy`), or in
	# the next invocation.  `sdbootutil-enroll` chains
	# --method=recovery-key and --method=tpm2.  The first one leaves
	# the recovery key here, and the second one uses it to authorize
	# the new slot
	keyctl timeout "$kawt_keyid" "$keyctl_timeout"
	created_keys+=("$kawt_keyid")
	# systemd tools do `keyctl request user "$kawt_name"`.  For some
	# reason, this means that the key must also be reachable from the
	# session keyring
	keyctl link "$kawt_keyid" @s
}

ask_password()
{
	local msg="$1"
	local -n nameref_pw="$2"
	# `read -p` prints the prompt only when the input is a terminal.
	# Without this check, a non-interactive caller gets an empty
	# password, and no hint of why
	[ -t 0 ] || err "\"$msg\" is required, but there is no terminal to ask for it"
	# A closed terminal (^D) makes `read` fail.  As a bare command
	# under `set -e`, that ends the script without a message.  The case
	# just above (no terminal at all) does print a message
	read -r -s -p "$msg: " nameref_pw || err "\"$msg\" was not provided"
	echo >&2
}

ask_new_password()
{
	local -; set +x
	local msg="$1"
	local -n nameref_pw="$2"
	local pw1 pw2
	while :; do
		ask_password "New $msg" pw1
		ask_password "Re-type $msg" pw2
		# Pressing only Enter is not an answer.
		# `systemd-cryptenroll` enrolls an empty password as a
		# keyslot that nothing can open afterwards, and it reports
		# success.  An empty TPM2 PIN makes it abort on an
		# assertion
		if [ -z "$pw1" ]; then
			warn "The $msg cannot be empty!"
		elif [ "$pw1" != "$pw2" ]; then
			warn "Inputs did't match!"
		else
			break
		fi
	done
	# shellcheck disable=SC2034
	nameref_pw="$pw1"
}

subvol_is_ro()
{
	[ -n "$have_snapshots" ] || return 1
	local subvol="${1:?}"

	while read -r line; do
		[ "$line" = "ro=true" ] && return 0
	done < <(btrfs prop get -t s "${subvol#"${subvol_prefix}"}" ro)
	return 1
}

detect_parent()
{
	local subvol="$1"
	[ -n "$have_snapshots" ] || return 0

	local parent_uuid
	parent_uuid="$(btrfs subvol show "${subvol#"${subvol_prefix}"}" | sed -ne 's/\s*Parent UUID:\s*//p')"
	[ "$parent_uuid" != '-' ] || return 0

	local -a parent_subvol_uuid
	local btrfs_subvol_status=0
	# shellcheck disable=SC2207
	parent_subvol_uuid=($(btrfs subvol show -u "$parent_uuid" "${subvol#"${subvol_prefix}"}" 2> /dev/null)) || btrfs_subvol_status=$?
	[ "$btrfs_subvol_status" = 0 ] || return 0
	parent_subvol="${parent_subvol_uuid[0]}"

	parent_snapshot="${parent_subvol#"${subvol_prefix}"/.snapshots/}"
	if [ "$parent_subvol" = "$parent_snapshot" ]; then
		unset parent_subvol parent_snapshot
	else
		parent_snapshot="${parent_snapshot%/snapshot}"
	fi

	dbg_var "parent_subvol"
	dbg_var "parent_snapshot"
}

snapshot_from_fsroot()
{
	local fsroot="${1#/}"
	local snapshot="${fsroot#"${subvol_prefix}"/.snapshots/}"

	[ "$snapshot" != "$fsroot" ] || return 0
	echo "${snapshot%%/*}"
}

detect_applied_snapshot()
{
	local fsroot
	local usr_snapshot=""

	[ -n "$have_snapshots" ] || return 0

	# With more than one `apply`, the mounts stack.  The last line is
	# the visible mount
	while read -r fsroot; do
		usr_snapshot="$(snapshot_from_fsroot "$fsroot")"
	done < <(findmnt --noheadings --output FSROOT /usr 2> /dev/null)

	[ -n "$usr_snapshot" ] || return 0
	[ "$usr_snapshot" != "$running_snapshot" ] || return 0
	echo "$usr_snapshot"
}

assert_snapshot()
{
	[ -n "$applied_snapshot" ] || return 0
	[ -z "$arg_default_snapshot" ] || return 0
	[ -z "$1" ] || return 0

	err "The running system is a mix of snapshot $running_snapshot (mounted in /) and" \
	    "snapshot $applied_snapshot (mounted in /usr), as left by 'transactional-update apply'." \
	    "\nRe-run the command with an explicit snapshot number, or with --default-snapshot" \
	    "to select the snapshot that will be booted next."
}

is_rootfs_crypt()
{
	local device
	read -r device < <(findmnt / -v -n -o SOURCE 2> /dev/null)
	[ -n "$device" ] && lsblk --noheadings --list --inverse -o TYPE "$device" 2> /dev/null | grep -qx crypt
}

get_rootfs()
{
	local rootfs_data

	case "$ROOTFS" in
		uuid) read -r rootfs_data < <(findmnt / -v -n -o UUID 2> /dev/null) ;;
		label) read -r rootfs_data < <(findmnt / -v -n -o LABEL 2> /dev/null) ;;
		partuuid) read -r rootfs_data < <(findmnt / -v -n -o PARTUUID 2> /dev/null) ;;
		partlabel) read -r rootfs_data < <(findmnt / -v -n -o PARTLABEL 2> /dev/null) ;;
		# "/dev/mapper/NAME" is used, as "/dev/dm-N" depends on the
		# order in which the devices were opened
		device) read -r rootfs_data < <(lsblk --noheadings --nodeps -o PATH "$(findmnt / -v -n -o SOURCE 2> /dev/null)" 2> /dev/null) ;;
		*)
			info "Can't determine rootfs ($ROOTFS). Using UUID as default"
			ROOTFS="uuid"
			read -r rootfs_data < <(findmnt / -v -n -o UUID 2> /dev/null)
			;;
	esac
	rootfs_data="${arg_rootfs_data:-$rootfs_data}"

	if [ "$ROOTFS" = "device" ]; then
		echo "$rootfs_data"
	else
		echo "${ROOTFS^^}=$rootfs_data"
	fi
}

get_all_rootfs()
{
	local rootfs rootfs_data kname path

	read -r rootfs_data < <(findmnt / -v -n -o SOURCE)
	rootfs="$rootfs_data"

	# Add every device of the file system.  btrfs can span several
	# devices.  Each device is added by two names: "/dev/<kernel
	# name>" and its path.  This is because older entries can use
	# "/dev/dm-N"
	read -r rootfs_data < <(findmnt / -v -n -o UUID)
	[ -z "$rootfs_data" ] || while read -r kname path; do
		rootfs="$rootfs|/dev/$kname|$path"
	done < <(lsblk --noheadings --raw -o KNAME,PATH -Q "UUID == \"$rootfs_data\"" 2> /dev/null)

	[ -z "$rootfs_data" ] || rootfs="$rootfs|UUID=$rootfs_data"

	read -r rootfs_data < <(findmnt / -v -n -o LABEL)
	[ -z "$rootfs_data" ] || rootfs="$rootfs|LABEL=$rootfs_data"

	read -r rootfs_data < <(findmnt / -v -n -o PARTUUID)
	[ -z "$rootfs_data" ] || rootfs="$rootfs|PARTUUID=$rootfs_data"

	read -r rootfs_data < <(findmnt / -v -n -o PARTLABEL)
	[ -z "$rootfs_data" ] || rootfs="$rootfs|PARTLABEL=$rootfs_data"

	echo "$rootfs"
}

sedrootflags()
{
	local subvol="$1"
	local root_param
	root_param="$(get_rootfs)"

	# The sed expressions do this:
	# - Delete everything before BOOT_IMAGE= and initrd=
	#   (see https://github.com/openSUSE/sdbootutil/issues/182)
	# - Delete BOOT_IMAGE= and initrd=
	# - Replace or add root=.  It names [PART]{UUID, LABEL}, or the
	#   mapped device
	# - Replace or add rootflags=, so it points to the right subvolume
	# - Delete systemd.machine_id= when /etc/machine-id is present
	#
	# From the sed manual:
	# ‘t’
	#     branch conditionally (that is: jump to a label) _only
	#     if_ a ‘s///’ command has succeeded since the last input
	#     line was read or another conditional branch was taken.
	#
	# Some expressions append a parameter.  When the replace before
	# them succeeded, the parameter was already there.  Then the "t"
	# command jumps over the append.  All the work is on one line, so
	# the condition is never reset by a new line.  An "empty" "t" jump
	# resets it after every s///
	local sed_arguments=("-e s/[ \t]\+/ /g"
		"-e s/^.*\(initrd=[^ ]*\|BOOT_IMAGE=[^ ]*\)\s*/\1 /"
		"-e s/\<\(BOOT_IMAGE\|initrd\)=[^ ]* \?//"
		"-e s/\$//;ta;:a"
		"-e s,\<root=[^ ]*,root=$root_param,;tb;s,\$, root=$root_param,;tc;:c;:b")
	[ -z "$subvol" ] || sed_arguments+=("-e s,\<rootflags=subvol=[^ ]*,rootflags=subvol=$subvol,;td;s,\$, rootflags=subvol=$subvol,;te;:e;:d")
	[ -n "$machine_id" ] || sed_arguments+=("-e s/\<systemd.machine_id=[^ ]* \?//")
	sed "${sed_arguments[@]}"
}

# Entries written before the "N_" prefix use "N@" in the version.
# systemd >= v262 warns about the "@" every time it parses the entry.
# It is only a warning.  The entry is accepted and sorts the same
bootctl_noise="^.*: Version string '[0-9]+@[^']*' is not a valid version, accepting anyway\.$"

# Run `bootctl` for the commands that parse the entries.  It hides the
# warning in "bootctl_noise".  The warning is kept when the user asked
# for more output, with `--verbose` or with SYSTEMD_LOG_LEVEL
bootctl_entries()
{
	if [ -n "$verbose" ] || [ -n "$SYSTEMD_LOG_LEVEL" ]; then
		bootctl "$@"
		return
	fi
	# Do not use `2> >(...)` here.  It opens /proc/self/fd/N with
	# O_CREAT, and SELinux denies it (dac_override, add_name)
	local rc=0
	bootctl "$@" 2> "$tmpdir/bootctl.err" || rc=$?
	grep -Ev "$bootctl_noise" "$tmpdir/bootctl.err" >&2 || :
	return "$rc"
}

# Write the entries to "$entryfile", through the filter "$@".  Without
# a filter, all the entries are written
update_entries()
{
	local filter=("${@:-cat}")
	bootctl_entries list --json=short | "${filter[@]}" > "$entryfile"
	dbg "Entry filter: ${filter[*]}"
	dbg_cat "$entryfile"
}

# The root devices of this system, see `get_all_rootfs`.  They do not
# change during a run, so they are computed only once
all_rootfs_cache=
all_rootfs()
{
	[ -n "$all_rootfs_cache" ] || all_rootfs_cache="$(get_all_rootfs)"
	echo "$all_rootfs_cache"
}

# The entries of this system come in two forms.  The ones that
# sdbootutil writes name the root and the snapshot in "options".  The
# ones made by "bootctl link" have no "options": their file name is
# "<entry token>-commit_<snapshot>.<version>.conf".  bootctl also lists
# the entries that the boot loader saw at boot.  When the file is gone,
# the entry is still listed, with the type "loader".  Only the type
# "type1" has a file, so only that type is taken by its name
update_entries_for_snapshot()
{
	local n="$1"
	[ -n "$n" ] || { update_entries_for_this_system; return; }
	local root
	root="$(all_rootfs)"

	# "root=" and "rootflags=" can be in any order.  Each one must
	# match a whole option
	update_entries jq "[.[]|select((.options // \"\" | test(\"(^| )root=(?:$root)( |$)\") and test(\"(^| )rootflags=subvol=${subvol_prefix}/.snapshots/$n/snapshot( |$)\"))
				   or (.type == \"type1\" and (.id|test(\"^${entry_token}-commit_${n}[.@+]\"))))]"
}

update_entries_for_this_system()
{
	local root
	root="$(all_rootfs)"

	update_entries jq "[.[]|select((.options // \"\"|test(\"root=(?:$root)(?: |$)\"))
				   or (.type == \"type1\" and (.id|startswith(\"${entry_token}-commit_\"))))]"
}

update_entries_for_extra()
{
	update_entries jq "[.[]|select((.linux//.efi//\"\")|startswith(\"/EFI/extra\"))]"
}

entry_conf_file()
{
	local kernel_version="${1:?}"
	local snapshot="$2"
	local tries="$3"

	# GRUB2 with the BLS patches does not follow the expected
	# ordering rules.  It only uses rpmvercmp() on the entry file
	# name.  To get an order, entries that are not read-only get the
	# prefix "system".  Read-only entries get the prefix "snapper".
	# "system" > "snapper", so the "system" entry is newer than any
	# "snapper" entry.
	#
	# Without snapshots there is only one entry per kernel version.
	# There is nothing to order it against, so no prefix is needed.
	# A prefix would also give the entry a second name.  kernel-install
	# and older versions of this script write the name without a
	# prefix.  Both files would then be in the ESP, for the same
	# system
	local prefix=""
	local subvol=""
	if [ -n "$have_snapshots" ] && ! is_transactional && is_grub2_bls; then
		subvol="${subvol_prefix}/.snapshots/${snapshot}/snapshot"
		if ! subvol_is_ro "$subvol"; then
			prefix="system"
		else
			prefix="snapper"
		fi
	fi

	echo "${prefix:+$prefix-}$entry_token-$kernel_version${snapshot:+-$snapshot}${tries:++$tries}.conf"
}

# An entry name without the ".conf" suffix and the boot counter.  This
# way a name from `bootctl` and a name from a boot loader can be
# compared.
#
# `bootctl` reports the ID with the ".conf" suffix.  It does not have
# the boot counter that `entry_conf_file` puts in the file name.
# grub2-bls writes "LoaderEntrySelected" the other way around: there is
# no suffix, and the counter is still there.  This is because grub2-bls
# records the name before "systemd-bless-boot" renames the file
entry_key()
{
	# The counter is "+3" until the loader counts a boot.  After
	# that it is "+2-1"
	local name="${1%.conf}"

	[[ ! "$name" =~ ^(.+)\+[0-9]+(-[0-9]+)?$ ]] || name="${BASH_REMATCH[1]}"

	echo "$name"
}

# The file of the entry of the kernel VERSION of SNAPSHOT, written by
# sdbootutil (see `entry_conf_file`)
find_conf_file()
{
	entry_file "$(entry_conf_file "${1:?}" "$2")"
}

# The only place that knows how a type#1 entry is written: a key, a run
# of blanks and the value.  There is one pair per line.  There can be
# comments and empty lines in between.  This prints the pairs, one per
# line.
#
# The pairs are printed one by one, not stored in an associative array.
# This is because a key can appear more than once.  "initrd" does when
# there is a microcode image.  The specification also allows several
# "options".
#
# A missing file is not an error.  Every caller treats an empty entry
# and a missing entry in the same way
entry_fields()
{
	local conf="${1:?}"
	local key value

	[ -f "$conf" ] || return 0

	while read -r key value; do
		[ -n "$key" ] || continue
		[ "${key:0:1}" != '#' ] || continue
		printf '%s %s\n' "$key" "$value"
	done < "$conf"
}

# The values of one key, in the order in which they appear
entry_field()
{
	local conf="${1:?}"
	local field="${2:?}"
	local key value

	while read -r key value; do
		[ "$key" = "$field" ] || continue
		printf '%s\n' "$value"
	done < <(entry_fields "$conf")
}

# The keys whose value is a file in the ESP.  Everything else in an
# entry is text that describes the system.  Different people own the
# two parts.  This script writes the files.  The command line can be
# edited by hand
entry_file_keys=" linux initrd devicetree uki extra "

entry_is_file_key()
{
	[ -n "${1-}" ] || return 1
	[[ $entry_file_keys == *" $1 "* ]]
}

# Every file that the entry references, as a path relative to the boot
# partition
entry_files()
{
	local conf="${1:?}"
	local key value

	while read -r key value; do
		! entry_is_file_key "$key" || printf '%s\n' "$value"
	done < <(entry_fields "$conf")
}

# Print the lines of the entry as they were written, split in two by
# `entry_is_file_key`.  "files" prints the lines that name a file.
# "text" prints everything else, with the comments and empty lines.
#
# `entry_fields` normalizes the blanks, and here that would be a bug.
# The result is written back as a boot entry.  An entry that differs
# from the one on disk only in its blanks is still a different file.
# It loses the name it had.  With the name, it also loses the boot
# counter of the kernel that did boot
entry_lines()
{
	local conf="${1:?}"
	local want="${2:?}"
	local line key

	[ -f "$conf" ] || return 0

	while IFS= read -r line; do
		read -r key _ <<<"$line"
		if entry_is_file_key "$key"; then
			[ "$want" != "files" ] || printf '%s\n' "$line"
		else
			[ "$want" != "text" ] || printf '%s\n' "$line"
		fi
	done < "$conf"
}

# The files that the entry names but that are not in the ESP.  Nothing
# else reports them.  `bootctl list` prints such an entry like any
# other.  The boot loader shows it in the menu.  So the first sign of
# the problem is a firmware error, on the boot that needed the entry
entry_missing_files()
{
	local conf="${1:?}"
	local path

	[ -f "$conf" ] || return 0

	while read -r path; do
		[ -e "${boot_root}${path}" ] || echo "$path"
	done < <(entry_files "$conf")
}

# Two jq functions.  "entry_version" gives the snapshot and the kernel
# version of an entry, as {snapshot, kernel}.  "snapshot" gives only the
# snapshot.  It reads it first from "rootflags=" in the options.
#
# The entries of sdbootutil have the version "N_<kernel>".  Older ones
# have "N@<kernel>".  The entries of "bootctl link" have the snapshot in
# the id ("-commit_N.").  Their version is "<commit>.<snapshot>.<kernel>",
# or "<commit>.<kernel>" without snapshots.  It can end in ".<variant>".
# Call jq with --arg snapshots "$have_snapshots"
# shellcheck disable=SC2016  # jq variables
jq_entry_version='def entry_version:
	if (.id // "" | test("-commit_[0-9]+[.@+]")) then
		(.id | capture("-commit_(?<n>[0-9]+)[.@+]") | .n) as $n
		| {snapshot: (if $snapshots != "" then $n else null end),
		   kernel: ((.version // "") | sub("^[0-9]+\\."; "")
			    | if $snapshots != "" then sub("^[0-9]+\\."; "") else . end
			    | sub("\\.[^.-]+$"; ""))}
	else
		(.version // "") | capture("((?<snapshot>[0-9]*)[@_])?(?<kernel>.*)")
	end;
def snapshot:
	((.options // "") | capture("rootflags=subvol=[^ ]*/\\.snapshots/(?<n>[0-9]+)/snapshot") | .n)
	// (entry_version | .snapshot);'

# Read a `bootctl list --json` array.  Print one line for each entry
# that does not boot, as "id|path|snapshot|version|missing".
#
# The fields are not separated by tabs.  A system without snapshots
# leaves the snapshot field empty.  `read` with a tab in IFS drops an
# empty field, because a tab counts as IFS whitespace.  None of the
# fields can contain "|", because FAT does not accept it in a name
#
# All the snapshots are checked, not only the current one.  This is on
# purpose.  An entry of another snapshot is in the same menu, and boots
# with the same key press.  Nothing else in this script looks at those
# entries.  "add-all-kernels" and `install_kernel` get a single snapshot,
# and they repair only that one
dangling_entries()
{
	local id path snapshot kernel_version missing

	while read -r id; do
		read -r path
		read -r snapshot
		read -r kernel_version
		[ "$snapshot" != "null" ] || snapshot=""
		missing="$(entry_missing_files "$path" | tr '\n' ' ')"
		[ -n "$missing" ] || continue
		printf '%s|%s|%s|%s|%s\n' \
		       "$id" "$path" "$snapshot" "$kernel_version" "${missing% }"
	done < <(jq -r --arg snapshots "$have_snapshots" "$jq_entry_version"'.[]
		       | select(.type? == "type1")
		       | select(.path != null)
		       | .id, .path, (entry_version | .snapshot, .kernel)')
}

# The entry that is on disk.  "cleanup --repair" sets it to the entry
# that it is about to write again.  It is empty everywhere else.  The
# other callers of `install_kernel` want it empty.  They create the
# entry or bring it up to date, so they want the generated content
keep_entry_conf=

# Rewrite a generated entry.  Only the lines that name a file keep the
# generated content.  All the other lines are taken from the old entry,
# exactly as they were.
#
# "linux", "initrd" and "devicetree" have the checksum of the files that
# were just written.  They are the reason for the repair.  The other
# lines are not ours to change.  An administrator can have edited the
# command line by hand.  The generated one would replace it without a
# word.  A boot entry that boots with other options than before is a
# failure that is impossible to diagnose later.  "update-all-entries"
# refreshes those lines, and the user must ask for it
keep_entry_fields()
{
	local conf="${1:?}"

	{
		entry_lines "$keep_entry_conf" text
		entry_lines "$conf" files
	} > "$conf.keep"
	mv "$conf.keep" "$conf"
}

# An entry is usable only if it points to this kernel and every file
# that it names is in the ESP
entry_is_complete()
{
	local conf="${1:?}"
	local linux_dst="${2:?}"
	local path

	while read -r path; do
		[ -e "${boot_root}${path}" ] || {
			dbg "$conf points to the missing ${boot_root}${path}"
			return 1
		}
	done < <(entry_files "$conf")

	# The entry must have an "initrd" line.  Some initrd for the
	# version in the ESP is not enough.  The entry can name an initrd
	# checksum that was already removed, and then it does not boot.
	# Also, `install_kernel` never writes an entry without an initrd.
	# So an entry without one was not written by us, and it does not
	# boot here either
	[ -n "$(entry_field "$conf" initrd)" ] || {
		dbg "$conf has no initrd line"
		return 1
	}

	# "$linux_dst" has the checksum of the kernel.  So a kernel that
	# is rebuilt with the same version does not match the "linux"
	# line of the entry of the previous build
	path="$(entry_field "$conf" linux)"
	[ "$path" = "$linux_dst" ] || {
		dbg "$conf points to ${path:-no kernel} and not to $linux_dst"
		return 1
	}
}

# There is no type#1 entry in the ESP.  Note that "nullglob" makes no
# difference between an empty and a missing directory.  This is what
# the caller expects.  Both mean that no kernel was installed yet
no_boot_entries()
{
	local confs=("${boot_root}/loader/entries/"*.conf)

	[ "${#confs[@]}" -eq 0 ]
}

settle_entry_token()
{
	local snapshot="$1"
	set_os_release "$snapshot"
	set_machine_id "$snapshot"
	case "$arg_entry_token" in
		""|auto)
			if [ -s '/etc/kernel/entry-token' ]; then
				read -r entry_token < '/etc/kernel/entry-token'
			else
				local var
				for var in machine_id os_release_IMAGE_ID os_release_ID; do
					entry_token="${!var}"
					[ -z "$entry_token" ] || break
				done
			fi
			;;
		machine-id)
			[ -n "$machine_id" ] || err "Couldn't determine machine-id"
			entry_token="$machine_id"
			;;
		os-id)
			# shellcheck disable=SC2154
			entry_token="$os_release_ID"
			[ -n "$entry_token" ] || err "Missing ID"
			;;
		os-image)
			# shellcheck disable=SC2154
			entry_token="$os_release_IMAGE_ID"
			[ -n "$entry_token" ] || err "Missing IMAGE_ID"
			;;
		literal:*)
			entry_token="${arg_entry_token#literal:}"
			;;
		*) err "Unexpected parameter for --entry-token=: $arg_entry_token" ;;
	esac
	[ -n "$entry_token" ] || err "Can't determine entry-token"

	dbg_var "entry_token"
	return 0
}

remove_kernel()
{
	local snapshot="$1"
	local kernel_version="$2"
	[ -n "$kernel_version" ] || err "Missing kernel version"

	info "Removing kernel $kernel_version"
	dbg_var "snapshot"

	[ -z "$TRANSACTIONAL_UPDATE" ] || [ -n "$arg_force" ] || {
		warn "Inside transactional-update. Removing kernels must be done outside the transaction"
		return 0
	}

	settle_entry_token "${snapshot}"
	local id old_default removed_default=
	old_default="$(get_default_entry 2> /dev/null)" || old_default=
	# The entry of the kernel and the initrd, and the ones of the UKIs
	for id in "$(entry_conf_file "$kernel_version" "$snapshot")" $(linked_entry_ids "$kernel_version" "$snapshot"); do
		entry_file "$id" > /dev/null || continue
		info "Removing boot entry $id"
		bootctl_entries unlink "$id"
		[ "$(entry_key "$id")" != "$(entry_key "$old_default")" ] || removed_default=1
	done

	# When the default entry is removed, `bootctl` marks a new
	# default.  The EFI variable (or the grubenv value) must still be
	# updated.  When another entry is the default, it stays as it is
	local default
	if [ -n "$removed_default" ] || [ -z "$old_default" ]; then
		default="$(get_default_bootctl)"
		if [ -z "$default" ]; then
			warn "Can't determine the new default entry"
		else
			set_default_entry "$default"
		fi
	fi

	# The PCR predictions must be updated after this
	update_predictions=1
}

install_with_rollback()
{
	local src="${1:?}"
	local dst="${2:?}"
	local old="${3:-$dst}"

	# Install `src` as `dst` when the file is new or different.  The
	# file can be present with the `old` name.  If it did not change,
	# it is kept.  Else it is installed with the new name (`dst`)
	if [ -e "$old" ]; then
		if cmp -s "$src" "$old"; then
			info "$old unchanged"
			return 0
		fi
		mv "$old" "$old.bak" || return "$?"
	fi
	rollback+=("$old")
	install -p -m 0644 -o root -g root "$src" "$dst" || return "$?"
	info "Installed $dst"
	record_esp_file "$dst"
}

# The ESP is not encrypted.  Anyone with physical access can change
# it.  The TPM2 policy is built from the files in the ESP.  So the next
# `update-predictions` would seal a file that someone else placed or
# changed, and that file would unlock the disk.  To stop this, every
# file that sdbootutil installs in the ESP and that is measured during
# boot is recorded with its digest in /var/lib/sdbootutil/esp-files.
# Only recorded files can be part of a new policy (`verify_esp_files`).
#
# Only the files that sdbootutil hashes itself are tracked.  The
# firmware components are read from the event log, and the TPM2
# validates the log.  A .pcrlock file shipped by a package is not
# computed by sdbootutil at all

# The name under which a file is recorded.  For an entry, the boot
# counter is removed.  Boot counting renames the entry: "+3.conf"
# becomes "+2-1.conf", and ".conf" once the boot is blessed.  The
# content stays the same
esp_file_key()
{
	local path
	path="$(realpath -m -s -- "${1:?}")"
	[[ "$path" != */loader/entries/*.conf ]] || path="${path%/*}/$(entry_key "${path##*/}").conf"
	echo "$path"
}

# The digest of the file when it was recorded.  Empty if the file was
# never recorded
esp_file_digest()
{
	local key digest path
	key="$(esp_file_key "$1")"
	[ -e "$esp_files" ] || return 0
	while read -r digest path; do
		[ "$path" != "$key" ] || echo "$digest"
	done < "$esp_files"
}

record_esp_file()
{
	local path="${1:?}"

	# The first prediction creates the record, from all the files in
	# the ESP.  Nothing is recorded before that.  A partial record
	# would make every file installed by an older version look
	# foreign
	[ -e "$esp_files" ] || return 0
	[ -f "$path" ] || return 0

	local key digest line_digest line_path
	key="$(esp_file_key "$path")"
	file_digest "$path" digest
	dbg "Recording $key ($digest)"
	{
		while read -r line_digest line_path; do
			[ "$line_path" = "$key" ] || echo "$line_digest  $line_path"
		done < "$esp_files"
		echo "$digest  $key"
	} > "$esp_files.new"
	mv "$esp_files.new" "$esp_files"
}

# Remember a file from the ESP that is hashed for the prediction
track_esp_file()
{
	echo "${1:?}" >> "$tmpdir/esp-files"
}

# Trust on first use.  The first prediction after an enrollment takes
# the files in the ESP as they are.  The same happens after an update
# from a version without the record.  A change made before that cannot
# be detected
seed_esp_files()
{
	local path

	mkdir -p "${esp_files%/*}"
	: > "$esp_files"
	while read -r path; do
		[ -n "$path" ] || continue
		record_esp_file "$path"
	done < <(
		cat "$tmpdir/esp-files"
		echo "${esp_root}/loader/loader.conf"
		echo "${esp_root}${esp_dst}/grubenv"
		bootctl_entries list --json=short | \
			jq -r --arg root "$boot_root" '.[] | select(.type == "type1") | .path, ($root + (.linux // "")), ($root + .initrd[]?), ($root + (.devicetree // "")),
					($root + (.uki // "")), (.addons[]? | $root + (.globalAddon // .localAddon))'
	)
}

# Every file hashed for the prediction must be as sdbootutil installed
# it.  With --force, a change made by the administrator is accepted
verify_esp_files()
{
	[ -s "$tmpdir/esp-files" ] || return 0

	if [ ! -e "$esp_files" ]; then
		info "Recording the files in the ESP that are measured during boot"
		seed_esp_files
		return 0
	fi

	local path digest
	local foreign=()
	while read -r path; do
		file_digest "$path" digest
		[ "$(esp_file_digest "$path")" = "$digest" ] || foreign+=("$path")
	done < <(sort -u "$tmpdir/esp-files")

	[ "${#foreign[@]}" -ne 0 ] || return 0

	# Put the components back as they were.  Else a later policy
	# would seal these files (fwupd, see `sync_pcrlock_policy`)
	[ -n "$arg_force" ] || {
		rm -rf /var/lib/pcrlock.d/*
		[ ! -d "$tmpdir/pcrlock.d" ] || cp -R "$tmpdir/pcrlock.d/." /var/lib/pcrlock.d/
	}
	[ -n "$arg_force" ] || \
		err "These files in the ESP were not installed by sdbootutil, or changed after it installed them:\n$(printf '  %s\n' "${foreign[@]}")\nA new TPM2 policy would unlock the disk when booting them.  If the change is expected, use --force"

	for path in "${foreign[@]}"; do
		warn "Accepting $path (--force)"
		record_esp_file "$path"
	done
}

update_snapper()
{
	snapper --jsonout --no-dbus list --disable-used-space > "$snapperfile"
	dbg_cat "$snapperfile"
}

# Change the title and the sort key of the system into the ones of a
# snapper snapshot.  They are in the variables named $1 and $2
set_snapper_title_and_sortkey()
{
	local -n sstsk_title="$1" sstsk_sort_key="$2"
	local snapshot="${3:?}" kernel_version="$4"
	[ -n "$have_snapshots" ] || return 0
	local type date desc important pre_num
	local snapshot_info

	[ -s "$snapperfile" ] || update_snapper

	# shellcheck disable=SC2046
	IFS="|" read -r type date desc important pre_num <<<\
		$(jq -r --arg snapshot "$snapshot" \
		'.["root"][]|select(.number==($snapshot|tonumber))|[.type,.date,(.description|gsub("\\|";"_")),.userdata.important,."pre-number"//""]|join("|")'\
		< "$snapperfile")

	if [ -z "$desc" ] && [ "$type" = "post" ] && [ -n "$pre_num" ]; then
		read -r desc <<<"$(jq -r --arg snapshot "$pre_num" '.["root"][]|select(.number==($snapshot|tonumber))|.description' < "$snapperfile")"
	fi

	if [ "$important" = "yes" ]; then important="*"; else important=""; fi
	[ "$type" = "single" ] && type=""
	snapshot_info="$snapshot,$kernel_version,$date${type:+, $type}${desc:+, $desc}"

	sstsk_title="Snapper: ${important}$sstsk_title ($snapshot_info)"
	sstsk_sort_key="snapper-$sstsk_sort_key"
}

set_os_release()
{
	local snapshot="$1"
	local subvol=""
	[ -z "$have_snapshots" ] || subvol="${subvol_prefix}/.snapshots/${snapshot}/snapshot"
	os_release_files=(
		"${subvol#"${subvol_prefix}"}/usr/lib/os-release"
		"${subvol#"${subvol_prefix}"}/etc/os-release"
	)

	for file in "${os_release_files[@]}"; do
		[ -f "$file" ] || continue
		eval "$(sed -ne '/^[A-Z_]\+=/s/^/os_release_/p' < "$file")"
		break
	done
}

set_machine_id()
{
	local snapshot="$1"
	local subvol=""
	[ -z "$have_snapshots" ] || subvol="${subvol_prefix}/.snapshots/${snapshot}/snapshot"
	machine_id_files=()
	if is_transactional && [ -z "$TRANSACTIONAL_UPDATE" ]; then
		[ -n "$snapshot" ] && machine_id_files+=("/var/lib/overlay/$snapshot/etc/machine-id")
	fi
	machine_id_files+=("${subvol#"${subvol_prefix}"}/etc/machine-id")

	for file in "${machine_id_files[@]}"; do
		if [ -s "$file" ]; then
			read -r machine_id < "$file"
			[ "$machine_id" != "uninitialized" ] || machine_id=
			[ -z "$machine_id" ] || break
		fi
	done
}

reuse_initrd()
{
	local snapshot="$1"
	local subvol="$2"
	local kernel_version="${3:?}"
	local conf

	[ -z "$arg_no_reuse_initrd" ] || return 1

	# Use the initrd of the entry of SNAPSHOT.  When there is no such
	# entry, use the initrd of the parent.  This avoids an expensive
	# regeneration.  The entry of the parent is named with the entry
	# token of the parent.  After that, the entry token of SNAPSHOT is
	# set again.  The caller uses it to write the title and the
	# machine-id of the new entry
	if ! conf="$(find_conf_file "$kernel_version" "$snapshot")"; then
		local parent_subvol parent_snapshot
		detect_parent "$subvol"
		[ -n "$parent_subvol" ] || return 1
		settle_entry_token "$parent_snapshot"
		conf="$(find_conf_file "$kernel_version" "$parent_snapshot")" || conf=
		settle_entry_token "$snapshot"
	fi

	if [ -n "$conf" ]; then
		local v
		while read -r v; do
			# An entry with a missing initrd does not boot
			[ -f "${boot_root}$v" ] || {
				dstinitrd=()
				break
			}
			info "Found existing initrd $v"
			dstinitrd+=("$v")
		done < <(entry_field "$conf" initrd)
		# Remember the entry, so that freeing space does not
		# remove the initrd reused here
		[ "${#dstinitrd[@]}" -eq 0 ] || {
			reused_entry="$conf"
			return 0
		}
	fi

	return 1
}

mount_chroot()
{
	local snapshot_dir="$1"

	# The list includes the root file system (usually the first
	# line).  It must appear in the mounts inside the chroot.  This
	# way dracut detects the file system type and adds its module
	findmnt -o TARGET,FSTYPE,FSROOT -Rv --json / > "$tmpdir/mounts"
	mount --bind "$snapshot_dir" "$snapshot_dir"
	# The bind is a peer of the shared /.snapshots mount.  Without
	# this, every mount below it would also appear on the host
	mount --make-slave "$snapshot_dir"
	# Register the chroot before mounting anything else.  Then
	# `cleanup` undoes the mounts when the loop fails in the middle
	chroot_dir="$snapshot_dir"
	local target fstype fsroot
	while IFS=$'\t' read -r target fstype fsroot; do
		[ "$fstype" = "btrfs" ] || [ "$fstype" = "vfat" ] || [ "$fstype" = "xfs" ] || [[ "$fstype" == ext* ]] || continue
		[ "$target" != "/" ] || continue
		[ "$target" = "/etc" ] && [ "$fstype" = "btrfs" ] && continue
		[[ "$target" != /.snapshots* ]] || continue
		[[ "$target" != /run/media/* ]] || continue
		# After a `transactional-update apply`, the running
		# system has /usr and /boot bind mounted from the new
		# default snapshot.  Those belong to another snapshot.
		# They must not hide the ones of "$snapshot_dir"
		[ -z "$(snapshot_from_fsroot "$fsroot")" ] || continue
		# Not every mount point of the running system is in the
		# snapshot.  One example is the directory that
		# `transactional-update` mounts under /tmp while a
		# transaction is open.  Another is any external media.
		# They are not needed to generate the initrd.  The
		# snapshot can be read-only, so the directory cannot be
		# created
		if [ ! -d "$snapshot_dir$target" ]; then
			dbg "Skipping $target, not present in $snapshot_dir"
			continue
		fi
		mountpoint --quiet "$snapshot_dir$target" || mount --bind "$target" "$snapshot_dir$target"
	done < <(jq -r '..|objects|select(has("target"))|[.target,.fstype,.fsroot]|@tsv' "$tmpdir/mounts")
	rm "$tmpdir/mounts"

	mount -t tmpfs -o size=10m tmpfs "$snapshot_dir/run"
	if [ -e /run/systemd/journal ]; then
		mkdir -p "$snapshot_dir/run/systemd/journal"
		mount --bind /run/systemd/journal "$snapshot_dir/run/systemd/journal"
	fi
	for i in proc dev sys tmp; do
		mount --bind "/$i" "$snapshot_dir/$i"
	done
}

umount_chroot()
{
	local snapshot_dir="$1"

	# The binds are peers of the host mounts.  So they receive the
	# mounts that the host creates in the meantime, like a FUSE
	# mount in /home.  Unmounting those copies would also unmount
	# the originals.  "--make-rslave" stops this
	mount --make-rslave "$snapshot_dir"
	umount -R "$snapshot_dir"
	chroot_dir=
}

mount_etc()
{
	local snapshot_dir="$1"

	# Do not mount inside a transactional-update shell
	[ -z "$TRANSACTIONAL_UPDATE" ] || return 0

	# Only overlayfs needs special treatment
	[ "$(findmnt --tab-file "${snapshot_dir}/etc/fstab" --noheadings --nofsroot --output FSTYPE /etc)" = "overlay" ] || return 0

	IFS=',' read -ra fields <<<\
	   "$(findmnt --tab-file "${snapshot_dir}/etc/fstab" --noheadings --nofsroot --output OPTIONS /etc | sed 's#/sysroot##g' | sed 's#:/etc,#:'"${snapshot_dir}"'/etc,#g')"

	local lower=""
	local upper=""
	for element in "${fields[@]}"; do
		IFS='=' read -r key value <<<"$element"
		[ "$key" = "lowerdir" ] && lower="$value"
		[ "$key" = "upperdir" ] && upper="$value"
	done

	mount overlay -t overlay -o ro,"lowerdir=${upper}:${lower}" "${snapshot_dir}/etc"
}

# The title and the sort key of the entry of the kernel VERSION in
# SNAPSHOT (in SUBVOL).  They are written in the variables named $1 and
# $2
# shellcheck disable=SC2034  # the namerefs are written for the caller
entry_title_and_sort_key()
{
	local -n etsk_title="$1" etsk_sort_key="$2"
	local snapshot="$3" subvol="$4" kernel_version="$5"

	etsk_title="${os_release_PRETTY_NAME:-Linux $kernel_version}"
	# The pretty name of Tumbleweed does not include the version
	# shellcheck disable=SC2154
	[ -n "$os_release_VERSION" ] || etsk_title+=" $os_release_VERSION_ID"
	# shellcheck disable=SC2154
	etsk_sort_key="$os_release_ID"

	if is_transactional && [ "$snapshot" = 1 ]; then
		etsk_title+=" (Initial Installation)"
	elif ! is_transactional && subvol_is_ro "$subvol"; then
		set_snapper_title_and_sortkey etsk_title etsk_sort_key "$snapshot" "$kernel_version"
	fi
}

pending_kernel_size()
{
	[ -n "$1" ] || {
		echo 0
		return 0
	}
	echo $(($(stat -c %s "$1") / 1024 + 1))
}

# The size of the initrds staged in DIR.  The initrds that are already
# in the directory ESP_DIR of the ESP do not count.  Their name is the
# checksum of the content, so the name tells if they are there
pending_initrds_size()
{
	local size=0
	local i=0 chksum
	while [ -e "$1/initrd-$i" ]; do
		calc_chksum "$1/initrd-$i"
		[ -n "${2:-}" ] && [ -e "${boot_root}$2/initrd-$chksum" ] || \
			size=$((size + $(stat -L -c %s "$1/initrd-$i")))
		((++i))
	done
	echo $((size / 1024 + 1))
}

pending_devicetree_size()
{
	local devicetree="$1"
	[ -n "$devicetree" ] || {
		echo 0
		return 0
	}
	echo $(($(stat -L -c %s "$devicetree") / 1024 + 1))
}

boot_space()
{
	local size
	size="$(findmnt --noheadings --bytes -o SIZE --target "${boot_root}" | head -n 1)"
	# This is called from a command substitution.  So `err` only ends
	# the sub-shell, and the caller sees the failure in the exit
	# status
	[[ "$size" =~ ^[0-9]+$ ]] || err "Can't determine the size of ${boot_root}"
	echo $((size / 1024))
}

boot_free_space()
{
	local avail
	avail="$(findmnt --noheadings --bytes -o AVAIL --target "${boot_root}" | head -n 1)"
	[[ "$avail" =~ ^[0-9]+$ ]] || err "Can't determine the free space in ${boot_root}"
	echo $((avail / 1024))
}

# The snapshots whose boot entries must be kept.  These are the default
# snapshot and the active one.  The snapshot where the kernel is being
# installed is also kept, if there is one.  One number per line
snapshots_in_use()
{
	local snapshot="$1"

	[ -n "$have_snapshots" ] || return 0

	{
		[ -z "$snapshot" ] || echo "$snapshot"
		[ -z "$root_snapshot" ] || echo "$root_snapshot"
		[ -s "$snapperfile" ] || update_snapper
		jq -r '.root[]|select(.active==true or .default==true)|.number' "$snapperfile"
	} | sort -un
}

# Print the ids of the boot entries that can be removed to make room in
# the ESP.  They are printed in the order in which they should be
# removed.
#
# `bootctl unlink` removes the kernel and the initrd only when the last
# entry that uses them is removed.  So the caller removes one entry at a
# time, and checks the free space after each removal.  Removing more
# than needed would leave older snapshots without a bootable entry.
#
# The order is:
#
#   1. Entries of the snapshots that are not in use.  The oldest
#      snapshot goes first.  Inside a snapshot, the oldest kernel goes
#      first
#   2. Entries of "root_snapshot" (the default snapshot, or the running
#      one), as a last resort
#
# These are never printed, so they are never removed:
#
#   - the default and the selected entries
#   - the entries of the snapshots in use.  The exception is
#     "root_snapshot": its entries are last in the list
#
# This works for both layouts.  In MicroOS the default snapshot is the
# newest one.  In Tumbleweed it is the oldest one.  In both cases the
# snapshots that are not in use are leftovers.  They can be removed from
# the oldest to the newest.  Snapshots created after a rollback are in
# the same group, and are removed the same way.
#
# The snapshot and the kernel version are read first from "options" and
# "linux", because sdbootutil writes those itself.  Only then are they
# read from "version" and "id".  Sometimes none of them can be parsed:
# a kernel from a third party repository, an entry written by another
# tool, or a system without snapshots.  Such an entry can still be
# removed, but it is sorted last in its group.  So it is removed only
# after the entries that have a known order
removable_entries()
{
	local snapshot="$1"

	local in_use
	mapfile -t in_use < <(snapshots_in_use "$snapshot")
	dbg "Snapshots that keep their boot entries: ${in_use[*]:-none}"

	update_entries_for_this_system

	# jq prints six columns to sort on.  The last one is the id:
	#
	#   1. 0 for a snapshot that is not in use, 1 for "root_snapshot"
	#   2. 0 if the snapshot number is known, 1 if it is not
	#   3. the snapshot number
	#   4. 0 if the kernel version is known, 1 if it is not
	#   5. the kernel version
	#   6. the id, to make the order stable
	#
	# The columns are never empty.  `read` and `sort` would merge two
	# tabs in a row, and the fields would shift
	jq -r --arg in_use "${in_use[*]}" --arg last "$root_snapshot" --arg keep "${reused_entry:-}" \
	   --arg snapshots "$have_snapshots" "$jq_entry_version"'
		def snapshot_of:
			snapshot
			// ((.id // "") | capture("-(?<n>[0-9]+)(\\+[0-9]+(-[0-9]+)?)?\\.conf$") | .n)
			// "";
		def kernel_of:
			((.linux // "") | capture("^/[^/]+/(?<k>[^/]+)/[^/]+$") | .k)
			// ((.version // "") | capture("^[0-9]+[@_](?<k>.+)$") | .k)
			// (select(.id // "" | test("-commit_[0-9]+[.@+]")) | entry_version | .kernel)
			// "";

		($in_use | split(" ") | map(select(. != ""))) as $in_use
		| .[]
		| select(.isDefault != true and .isSelected != true and .path != $keep)
		| snapshot_of as $s
		| kernel_of as $k
		| select(($in_use | index($s)) == null or $s == $last)
		| [ (if $s == $last then 1 else 0 end),
		    (if $s == "" then 1 else 0 end),
		    (if $s == "" then 0 else ($s | tonumber) end),
		    (if $k == "" then 1 else 0 end),
		    (if $k == "" then "-" else $k end),
		    .id ]
		| @tsv
	' < "$entryfile" |
		sort -t$'\t' -k1,1n -k2,2n -k3,3n -k4,4n -k5,5V -k6,6 |
		cut -f6
}

# Remove the files in the ESP that no boot entry uses anymore.
#
# This is a best effort cleanup.  It is never the main work of the
# caller: the kernel is already installed, or the entries are already
# removed.  So its exit status must not stop the caller.  Else a failed
# cleanup would abort `install_kernel` after the entry is written, but
# before the PCR predictions are scheduled.  Then the next boot cannot
# unseal.  This is why it always does "return 0".
#
# The reason of a failure is still shown.  `bootctl` also prints the
# normal "Cleaning <esp>" line in stderr.  So stderr is captured, and it
# is shown only when the cleanup failed
bootctl_cleanup()
{
	dbg "Calling bootctl cleanup"

	local output
	output="$(bootctl -q cleanup 2>&1)" || \
		warn "Failed to clean up ${boot_root}${output:+: $output}"
	return 0
}

# Try to make room in the ESP for "required_size" KB.  The caller checks
# the exit status (`make_free_space ... || err ...`).  So `set -e` is
# not active here.  Every failure must be reported here.  Else it is
# shown as a lack of space
make_free_space()
{
	local snapshot="$1"
	local required_size="$2"

	[[ "$required_size" =~ ^[0-9]+$ ]] || {
		warn "Can't determine the size of the new kernel and initrd"
		return 1
	}

	local total_space free_space
	total_space="$(boot_space)" || return 1
	free_space="$(boot_free_space)" || return 1

	# The extra size is a reserve that sdbootutil tries to keep
	# free in the ESP.  It is a goal, not a requirement.  It must
	# never block the installation of a kernel that still fits
	local required_size_extra wanted_size
	required_size_extra=$((total_space * ESP_FREE_SPACE / 100))
	wanted_size=$((required_size + required_size_extra))

	info "Required free space in ESP: ${required_size}KB + ${required_size_extra}KB (${ESP_FREE_SPACE}% ESP size)"

	# Stop here when there is already enough free space
	[ "$wanted_size" -gt "$free_space" ] || return 0

	bootctl_cleanup

	# Remove the entries one by one, from the least to the most
	# valuable one, until there is enough space.  The free space is
	# checked after every removal.  This is because `bootctl unlink`
	# frees the kernel and the initrd only when the last entry that
	# uses them is gone
	local id
	while read -r id; do
		free_space="$(boot_free_space)" || return 1
		dbg "Free space in the ESP: $free_space KB"
		[ "$wanted_size" -gt "$free_space" ] || return 0
		info "Removing boot entry $id"
		bootctl unlink "$id" || warn "Failed to remove the boot entry $id"
	done < <(removable_entries "$snapshot")

	free_space="$(boot_free_space)" || return 1
	dbg "Free space in the ESP after deallocation: $free_space KB"

	[ "$wanted_size" -gt "$free_space" ] || return 0

	# The reserve is not free, but the new kernel and initrd still
	# fit.  Warn about it, because the next installation can fail.
	# Do not block this one
	[ "$required_size" -gt "$free_space" ] || {
		warn "Only ${free_space}KB free in ${boot_root}, below the ${ESP_FREE_SPACE}% reserve"
		warn "Remove the old kernels, or increase the size of ${boot_root}"
		return 0
	}

	warn "Needed ${required_size}KB in ${boot_root}, but only ${free_space}KB are free"
	warn "There are no more boot entries that can be removed automatically"
	return 1
}

make_free_space_for_kernel()
{
	local snapshot="$1"
	local kernel="$2"
	local initrds="$3"
	local devicetree="${4:-}"
	local initrds_dst="${5:-}"

	# Calculate the required size.  All sizes are in KB, to avoid
	# big numbers
	local free_space total_size
	total_size=$(($(pending_kernel_size "$kernel") + $(pending_initrds_size "$initrds" "$initrds_dst") + $(pending_devicetree_size "$devicetree")))

	make_free_space "$snapshot" "$total_size"
}

resolve_devicetree_source()
{
	local subvol="$1"
	local kernel_version="$2"
	local kernel_package_version="${kernel_version%-*}"
	local devicetree_source="${DEVICETREE_SOURCE:-}"

	[ -n "$devicetree_source" ] || return 0
	devicetree_source="${devicetree_source//%K/$kernel_version}"
	devicetree_source="${devicetree_source//%V/$kernel_package_version}"
	[[ "$devicetree_source" == '/'* ]] || err "DEVICETREE_SOURCE must be an absolute path"

	local snapshot_prefix="${subvol#"${subvol_prefix}"}"
	devicetree_source="$snapshot_prefix$devicetree_source"
	[ -f "$devicetree_source" ] || err "Can't find device tree blob $devicetree_source"
	[ -r "$devicetree_source" ] || err "Device tree blob is not readable: $devicetree_source"
	echo "$devicetree_source"
}

# True when the script does not work on the running system.  This
# happens in two cases.  The system can be mounted somewhere else and
# entered with `chroot`, as in the installer or in a `zypper --root`
# transaction.  Or it can be an image that is built inside a container
foreign_system()
{
	[ -z "$in_buildroot" ] || return 0

	# `--chroot` compares "/" with "/proc/1/root".  When "/proc" is
	# not mounted, it cannot compare them, and it also reports a
	# chroot.  This is what the caller expects.  Without "/proc"
	# there is no "/proc/cmdline" to use either
	systemd-detect-virt -q --chroot && return 0
	systemd-detect-virt -q --container && return 0

	return 1
}

# The files of the configuration directory "dir" in "root" ("" for
# "/"), one per line.  This follows the UAPI configuration files
# specification.  The files are in "/usr/lib/dir" and "/etc/dir".  A
# file in "/etc" replaces the file with the same name in "/usr/lib".
# The files are sorted by name, wherever they are.  An empty file or a
# symlink to "/dev/null" masks the file.  A masked file is listed too,
# and the caller skips it.  Only the names that match "glob" count.
# Directories, hidden files and the files that rpm or an editor leave
# behind never count
uapi_files()
{
	local root="$1"
	local dir="$2"
	local glob="${3:-*}"

	local -A by_name=()
	local i
	for i in "$root/usr/lib/$dir"/$glob "$root/etc/$dir"/$glob; do
		[ ! -d "$i" ] || continue
		case "$i" in
			*.rpmsave|*.rpmnew|*.rpmorig|*~) continue ;;
		esac
		by_name["${i##*/}"]="$i"
	done

	[ "${#by_name[@]}" -gt 0 ] || return 0
	local name
	while IFS= read -r name; do
		echo "${by_name[$name]}"
	done < <(printf '%s\n' "${!by_name[@]}" | sort)
}

# The base file of the kernel command line in "root", if there is one.
# The file in "/etc" replaces the one in "/usr/lib".  When it is empty,
# it masks it
kernel_cmdline_base()
{
	local root="$1"

	local i
	for i in "$root/etc/kernel/cmdline" "$root/usr/lib/kernel/cmdline"; do
		[ -e "$i" ] || [ -L "$i" ] || continue
		echo "$i"
		break
	done
}

# List every file that adds to the kernel command line of the entry of
# "subvol", in the order in which they are joined.  First the base
# file, then the drop-ins that extend it.  Fails when none of them
# configures a command line
#
# All the files come from one system.  This is the snapshot of the
# entry.  When the snapshot configures nothing, it is the running
# system.  Mixing both would repeat the drop-ins that are in the two.
# It would also lose the masks of one of them
kernel_cmdline_files()
{
	local subvol="$1"

	# The running snapshot is "/".  A system without snapshots is
	# "/" too
	local root="${subvol#"${subvol_prefix}"}"
	[ "$root/" -ef / ] && root=

	if [ -n "$root" ] && [ -z "$(kernel_cmdline_base "$root")$(uapi_files "$root" kernel/cmdline.d)" ]; then
		dbg "No kernel command line in $root, using the one of the running system"
		root=
	fi

	local base
	local dropins=()
	base="$(kernel_cmdline_base "$root")"
	mapfile -t dropins < <(uapi_files "$root" kernel/cmdline.d)

	# "/proc/cmdline" is the command line of the running kernel.  So
	# it can replace a missing base file only when the entry is of
	# the running system.  Inside the installer, it describes the
	# installation medium.  The installed system would get
	# parameters like "Y2DEBUG=1", "linuxrc.debug" or
	# "console=ttyS0".  It would also miss the parameters that the
	# installer is expected to provide, like "quiet"
	if [ -n "$base" ] || [ -n "$root" ]; then
		dbg "Using the kernel command line in ${root:-/}"
	elif foreign_system; then
		dbg "Ignoring /proc/cmdline: not the running system"
	else
		base=/proc/cmdline
	fi

	# A masked base file counts as a configured command line, and it
	# is empty.  The check is not "-s", because the size of
	# "/proc/cmdline" is not always known
	local found=
	[ -z "$base" ] || found=1
	[ ! -f "$base" ] || echo "$base"

	local i
	for i in "${dropins[@]}"; do
		[ -f "$i" ] && [ -s "$i" ] || continue
		echo "$i"
		found=1
	done

	[ -n "$found" ]
}

# The parameters of a command line, one per line.  A value in double
# quotes can have spaces, as for the kernel
cmdline_params()
{
	local cmdline="$1"

	local param="" quoted="" c i
	for ((i = 0; i < ${#cmdline}; i++)); do
		c="${cmdline:i:1}"
		if [ "$c" = '"' ]; then
			if [ -n "$quoted" ]; then quoted=; else quoted=1; fi
		elif [ -z "$quoted" ] && [[ "$c" == [[:space:]] ]]; then
			[ -z "$param" ] || echo "$param"
			param=
			continue
		fi
		param+="$c"
	done
	[ -z "$param" ] || echo "$param"
}

# The kernel command line from the files of SUBVOL.  "root=" and
# "rootflags=" are not settled yet (see `sedrootflags`)
kernel_cmdline()
{
	local subvol="$1"

	local cmdline_files=()
	mapfile -t cmdline_files < <(kernel_cmdline_files "$subvol")

	# Only `kernel_cmdline_files` decides when "/proc/cmdline" is the
	# base.  Then it is the first file
	local base=
	if [ "${cmdline_files[0]:-}" = /proc/cmdline ]; then
		base="$(< /proc/cmdline)"
		cmdline_files=("${cmdline_files[@]:1}")
	fi

	# Take every line of the files, but not the comments.  The last
	# line is taken too when it does not end in a newline
	local options=()
	local i line
	for i in "${cmdline_files[@]}"; do
		dbg_cat "$i"
		while read -r line || [ -n "$line" ]; do
			[ -n "$line" ] && [[ "$line" != '#'* ]] || continue
			options+=("$line")
		done < "$i"
	done
	local cmdline="${options[*]}"

	# "/proc/cmdline" already has the drop-ins of the boot.  Take them
	# out before adding them again.  Else the entry would get one more
	# copy of them after every boot
	if [ -n "$base" ]; then
		local -A dropin_params=()
		local param params=()
		while IFS= read -r param; do
			dropin_params["$param"]=1
		done < <(cmdline_params "$cmdline")
		while IFS= read -r param; do
			[ -n "${dropin_params["$param"]:-}" ] || params+=("$param")
		done < <(cmdline_params "$base")
		cmdline="${params[*]}${cmdline:+ $cmdline}"
	fi

	echo "$cmdline"
}

# The options of the boot entry of SUBVOL.  They are generated even when
# there is no command line at all.  `sedrootflags` adds "root=" and
# "rootflags=".  They are the minimum needed to boot
create_boot_options()
{
	local subvol="$1" boot_options
	boot_options="$(kernel_cmdline "$subvol" | sedrootflags "$subvol")"
	echo "${boot_options# }"
}

# The command line of the addon of a UKI entry of SUBVOL.  It is the
# same for every kind of UKI.  It has the "rootflags=" of the snapshot.
# With UKI_CMDLINE, it also has the options of the kernel command line
# of the system.  "root=" is not here.  It is in the addon of the root,
# when it is needed (see `update_dps_addon`)
uki_addon_cmdline()
{
	local subvol="$1" param params=()
	if [ "$UKI_CMDLINE" = "no" ]; then
		[ -z "$subvol" ] || echo "rootflags=subvol=$subvol"
		return 0
	fi
	while read -r param; do
		[[ "$param" != root=* ]] || continue
		params+=("$param")
	done < <(cmdline_params "$(create_boot_options "$subvol")")
	echo "${params[*]}"
}

# The path of the addon of the root, used by every UKI.  It is in the
# directory where systemd-stub loads addons for any UKI that it starts
dps_addon_path()
{
	echo "${boot_root}/loader/addons/${entry_token}-dps.addon.efi"
}

# The UKIs in the ESP that are not of this system.  These are the ones
# in /EFI/Linux, and the UKI entries of another entry token.  The addon
# of the root changes their boot too.  This is because systemd-stub
# loads it for every UKI
dps_addon_others()
{
	bootctl_entries list --json=short 2> /dev/null | \
		jq -r --arg token "$entry_token-" '.[] | select(.type == "type2" or (.uki and (.id | startswith($token) | not))) | .id'
}

# True when the addon of the root has the crypttab that it would get
# now (DPS as in `addon_crypttab`).  A new encrypted device in
# /etc/crypttab changes the crypttab.  Then the addon must be written
# again
dps_addon_crypttab_current()
{
	local dps="$1" lines addon
	lines="$(addon_crypttab "$dps")"
	addon="$(dps_addon_path)"
	# With DPS and no other device for the initrd, there must be no
	# addon
	if [ -n "$dps" ] && [ -z "$lines" ]; then
		[ ! -e "$addon" ]
		return
	fi
	[ -e "$addon" ] && [ "$(addons_crypttab "${addon#"$boot_root"}")" = "$lines" ]
}

# Write the addon of the root, used by every UKI.  It has an initrd with
# the crypttab that dracut would use.  This is because the initrd of a
# UKI has no crypttab.  When the discovery does not find the root (see
# `dps_root_problem`), the addon also has "root=".  When the discovery
# finds the root, it opens the root by itself.  Then the addon is needed
# only when the initrd must open other devices too.
#
# The addon is the same for every UKI, local or from the packages, and
# for every snapshot.  So there is only one.  It is written again when
# its content changes, for example after adding an encrypted device.
# It is removed when there are no UKIs.  This runs once per run
dps_addon_done=
update_dps_addon()
{
	[ -z "$dps_addon_done" ] || return 0
	dps_addon_done=1
	local out cmdline="" dps="" lines=""
	out="$(dps_addon_path)"
	if uki_selected; then
		[ -n "$(dps_root_problem)" ] || dps=1
		lines="$(addon_crypttab "$dps")"
	fi
	if ! uki_selected || { [ -n "$dps" ] && [ -z "$lines" ]; }; then
		[ -e "$out" ] || return 0
		info "Removing $out"
		rm -f "$out"
		update_predictions=1
		return 0
	fi

	uki_keys
	[ -n "$dps" ] || cmdline="root=$(get_rootfs)"
	crypttab_cpio "$tmpdir/dps.cpio" "$lines"
	# The same content and the same key make the same file.  So when
	# the new addon is the same as the one in the ESP, there is
	# nothing to do.  When the crypttab, the root, the key or the stub
	# change, the file changes, and it is written again
	build_addon "$cmdline" "$tmpdir/dps.addon.efi" "$tmpdir/dps.cpio"
	if cmp -s "$tmpdir/dps.addon.efi" "$out"; then
		rm -f "$tmpdir"/dps.*
		return 0
	fi
	info "Writing $out"
	# Do not use `install_with_rollback` here.  Its rollback list is
	# for the install of one kernel.  The addon is for every kernel
	mkdir -p "${out%/*}"
	install -p -m 0644 -o root -g root "$tmpdir/dps.addon.efi" "$out" || err "Cannot write $out"
	record_esp_file "$out"
	rm -f "$tmpdir"/dps.*
	update_predictions=1
}

# The name of the entry that "bootctl link" makes for the kernel
# VERSION of SNAPSHOT.  Without snapshots, the commit is always 1
linked_entry_id()
{
	local kernel_version="$1" snapshot="$2" variant="${3:-}"
	echo "$entry_token-commit_${snapshot:-1}.${snapshot:+${snapshot}.}$kernel_version${variant:+.$variant}.conf"
}

# The ids of the entries of the UKIs of the kernel VERSION of SNAPSHOT.
# There is one entry for UKI="local".  With UKI="yes" there is one entry
# per variant.  A UKI with profiles has one more entry per profile,
# named "<id>@N"
linked_entry_ids()
{
	local base f id
	base="$(linked_entry_id "$1" "$2")"
	base="${base%.conf}"
	for f in "${boot_root}/loader/entries/$base.conf" "${boot_root}/loader/entries/$base"[.@+]*.conf; do
		[ -e "$f" ] || continue
		id="${f##*/}"
		echo "$(entry_key "$id").conf"
	done | sort -u
}

# The file of the entry ID, with or without a boot counter
entry_file()
{
	local id="${1%.conf}" f
	for f in "${boot_root}/loader/entries/$id.conf" "${boot_root}/loader/entries/$id+"*.conf; do
		[ -e "$f" ] || continue
		echo "$f"
		return 0
	done
	return 1
}

# Remove the entries of the kernel VERSION in SNAPSHOT that are not in
# KEPT...  KEPT are the entries just written.  The other entries are of
# another kind (kernel and initrd, local UKI, UKIs of the packages), or
# of a variant that is gone.  After a change of UKI they do not boot,
# because the TPM2 slots are made for the new kind.  The booted entry is
# not removed.  If the new entry does not boot, the booted one is the
# way back.  A later run removes it.  If a removed entry was the default
# entry, the first of KEPT becomes the default.  This also happens when
# the old default is the booted entry, and so it is not removed
unlink_other_entries()
{
	local kernel_version="$1" snapshot="$2"
	shift 2
	local kept=" " id selected default
	for id; do
		kept+="$(entry_key "$id") "
	done

	selected="$(entry_key "$(bli_efi_var_get "LoaderEntrySelected" 2> /dev/null)")"
	default="$(get_default_entry 2> /dev/null)" || default=
	for id in "$(entry_conf_file "$kernel_version" "$snapshot")" $(linked_entry_ids "$kernel_version" "$snapshot"); do
		[[ "$kept" != *" $(entry_key "$id") "* ]] || continue
		entry_file "$id" > /dev/null || continue
		[ "$(entry_key "$id")" != "$(entry_key "$default")" ] || set_default_entry "$1"
		[ "$(entry_key "$id")" != "$selected" ] || continue
		bootctl_entries unlink "$id"
	done
}

# The entry of SNAPSHOT (in SUBVOL) or of its parent, for the kernel
# VERSION.  It is printed only if its UKI has the command line OPTIONS
# and the kernel LINUX.  This way the entry of the snapshot keeps its
# UKI when only its addon changes.  A new snapshot uses the UKI of its
# parent.  `reuse_initrd` does the same with the initrd
reusable_uki()
{
	local snapshot="$1" subvol="$2" kernel_version="$3" cmdline="$4" linux="$5"
	local parent_subvol parent_snapshot entry snap
	detect_parent "$subvol"
	for snap in "$snapshot" "$parent_snapshot"; do
		[ -n "$snap" ] || continue
		entry="$(entry_file "$(linked_entry_id "$kernel_version" "$snap")")" || continue
		! uki_matches "$entry" "$cmdline" "$linux" || { echo "$entry"; return 0; }
	done
	return 1
}

# Whether the UKI of the entry ENTRY is in the ESP, and matches.  It
# must have the command line CMDLINE and the kernel LINUX.  It must also
# have the key of the current signed PCR 11 policy.  Without FDE there
# is no key
uki_matches()
{
	local entry="$1" cmdline="$2" linux="$3" path key="" ret=1
	path="$(entry_field "$entry" uki)"
	[ -n "$path" ] && [ -e "${boot_root}$path" ] || return 1
	[ ! -e "$credstore/tpm2-pcr-initrd-private-key.pem" ] || key="$(< "$pcr_public_key")"
	# objcopy writes a new file and renames it over its output.  So the
	# output is never /dev/stdout: objcopy could replace that link with a
	# file
	objcopy -O binary --only-section=.cmdline "${boot_root}$path" "$tmpdir/uki-cmdline"
	# A kernel rebuilt with the same version makes a new UKI
	objcopy -O binary --only-section=.linux "${boot_root}$path" "$tmpdir/uki-linux"
	objcopy -O binary --only-section=.pcrpkey "${boot_root}$path" "$tmpdir/uki-pcrpkey"
	if [ "$(< "$tmpdir/uki-cmdline")" = "$cmdline" ] && cmp -s "$tmpdir/uki-linux" "$linux" && \
	   [ "$(< "$tmpdir/uki-pcrpkey")" = "$key" ]; then
		ret=0
	fi
	rm -f "$tmpdir/uki-cmdline" "$tmpdir/uki-linux" "$tmpdir/uki-pcrpkey"
	return "$ret"
}

# Make the entry of the kernel VERSION of SNAPSHOT (in SUBVOL) with a
# UKI built here (UKI="local").  Every snapshot shares the UKI.  The
# snapshot and its rootflags are in an addon (see `link_uki`)
install_local_uki()
{
	local snapshot="$1" subvol="$2" kernel_version="$3" src="$4"
	local reused_entry=

	# The command line of the UKI is fixed.  The addon of the entry has
	# the rest (see `uki_addon_cmdline`).  The command line is not empty.
	# This is because with Secure Boot, systemd-stub ignores the command
	# line of the boot loader only when the UKI has one.  "ro" is what
	# systemd does with "root="
	local boot_options="ro"

	# Use the UKI of the entry, the one of the parent snapshot, or a new
	# one.  The name of the UKI has the hash of its content, so "link"
	# shares it between entries.  The addon of the entry can change while
	# the UKI stays the same.  So `link_uki` decides if there is something
	# to do
	local uki=""
	[ -n "$arg_no_reuse_initrd$arg_force" ] || \
		reused_entry="$(reusable_uki "$snapshot" "$subvol" "$kernel_version" "$boot_options" "$src")" || reused_entry=""
	if [ -n "$reused_entry" ]; then
		# Freeing space must not remove the entry and its UKI.  So "link"
		# gets a copy.  The UKI in the ESP goes away when `link_uki`
		# unlinks the entry of this kernel to link it again
		uki="$(entry_field "$reused_entry" uki)"
		info "Reusing ${boot_root}$uki"
		cp "${boot_root}$uki" "$tmpdir/${uki##*/}"
		uki="$tmpdir/${uki##*/}"
	else
		stage_initrd "$snapshot" "$subvol" "$kernel_version" "${src%/*}/initrd" uki
		build_uki "$src" "$tmpdir/initrd-0" "$boot_options" "${subvol#"${subvol_prefix}"}/usr/lib/os-release" \
			"$kernel_version" "$tmpdir/uki-signed.efi"
		uki="$(stage_hashed "$tmpdir/uki-signed.efi" "$kernel_version" .efi)"
		rm -f "$tmpdir/initrd-0"
	fi

	link_uki "$snapshot" "$subvol" "$kernel_version" "$uki" "" ""
	unlink_other_entries "$kernel_version" "$snapshot" "$(linked_entry_id "$kernel_version" "$snapshot")"
}

# Stage SRC as NAME-<hash>SUFFIX in $tmpdir, for "bootctl link".
# "link" takes the file names as they are.  It keeps a file whose name
# is already in the ESP.  The files of the packages repeat the same
# names for every kernel, so the hash is added.  The staged file is a
# symlink, because "link" reads the file it points to
stage_hashed()
{
	local src="$1" name="$2" suffix="$3" sum
	read -r sum _ < <(sha256sum "$src")
	ln -sf "$(realpath "$src")" "$tmpdir/$name-${sum:0:16}$suffix"
	echo "$tmpdir/$name-${sum:0:16}$suffix"
}

# Make the entries of the UKIs of the packages for the kernel VERSION
# of SNAPSHOT (in SUBVOL).  There is one entry per variant, with its
# addons.  Without a UKI the function fails.  Then the caller makes the
# entry of the kernel and the initrd.  Nothing is built here, so
# nothing is rebuilt either
install_distro_ukis()
{
	local snapshot="$1" subvol="$2" kernel_version="$3"
	local ukis=()
	ukis=("${subvol#"${subvol_prefix}"}/usr/lib/modules/$kernel_version"/vmlinuz-*.efi)
	[ -e "${ukis[0]}" ] || {
		warn "Kernel $kernel_version has no UKI, using the kernel and the initrd.  Install a kernel-${kernel_version##*-}-uki-<variant> package"
		return 1
	}

	local uki variant addon extras several="" ids=()
	[ "${#ukis[@]}" -eq 1 ] || several=1
	for uki in "${ukis[@]}"; do
		variant="${uki##*/vmlinuz-}"
		variant="${variant%.efi}"
		ids+=("$(linked_entry_id "$kernel_version" "$snapshot" "$variant")")
		extras=()
		for addon in "$uki.extra.d"/*.addon.efi; do
			[ -e "$addon" ] || continue
			extras+=("$(stage_hashed "$addon" "$(basename "$addon" .addon.efi)" .addon.efi)")
		done
		link_uki "$snapshot" "$subvol" "$kernel_version" \
			"$(stage_hashed "$uki" "$kernel_version-$variant" .efi)" "$variant" "$several" "${extras[@]}"
	done
	unlink_other_entries "$kernel_version" "$snapshot" "${ids[@]}"
}

# The name of the addon with the command line CMDLINE.  The name
# changes with the command line and with the key that signs it.  This
# is because "link" keeps the file whose name is already in the ESP
addon_name()
{
	local sum
	read -r sum _ < <({ echo -n "$1"; cat "$secureboot_certificate"; } | sha256sum)
	echo "cmdline-${sum:0:16}.addon.efi"
}

# Make the entry of the UKI of the kernel VERSION of SNAPSHOT (in
# SUBVOL) with "bootctl link".  The entry has the UKI, the addons
# EXTRA..., and the addon of the snapshot (see `uki_addon_cmdline`).
# The addon of the root is not linked (see `update_dps_addon`).
# VARIANT is in the id of the entry.  It is also in the title when
# SEVERAL variants are installed
link_uki()
{
	local snapshot="$1" subvol="$2" kernel_version="$3" uki="$4" variant="$5" several="$6"
	shift 6
	local id f size=0 extra=()
	id="$(linked_entry_id "$kernel_version" "$snapshot" "$variant")"

	local title sort_key
	entry_title_and_sort_key title sort_key "$snapshot" "$subvol" "$kernel_version"
	[ -z "$several" ] || title="$title ($variant)"

	# The addon of the entry is built once.  It serves every kernel of
	# the snapshot (see `addon_name`).  "link" gets a copy, because the
	# addon in the ESP can go away.  It can go with the entry unlinked
	# below, or when space is freed
	local addon cmdline
	cmdline="$(uki_addon_cmdline "$subvol")"
	if [ -n "$cmdline" ]; then
		addon="$tmpdir/$(addon_name "$cmdline")"
		if [ -e "${boot_root}/$entry_token/${addon##*/}" ]; then
			cp "${boot_root}/$entry_token/${addon##*/}" "$addon"
		else
			build_addon "$cmdline" "$addon"
		fi
		set -- "$@" "$addon"
	fi

	# Nothing to do when the entry has the same files already
	local entry wanted have
	if [ -z "$arg_force" ] && entry="$(entry_file "$id")"; then
		wanted="$(for f in "$uki" "$@"; do echo "${f##*/}"; done | sort)"
		have="$(entry_field "$entry" uki; entry_field "$entry" extra)"
		have="$(for f in $have; do echo "${f##*/}"; done | sort)"
		if [ "$wanted" = "$have" ] && [ -z "$(entry_missing_files "$entry")" ]; then
			info "UKI of $kernel_version${variant:+ ($variant)} already in the ESP"
			return 0
		fi
	fi

	# Only the files that are not in the ESP need space.  They are
	# recorded after "link" copies them
	local added=()
	for f in "$uki" "$@"; do
		[ ! -e "${boot_root}/$entry_token/${f##*/}" ] || continue
		size=$((size + $(stat -L -c %s "$f")))
		added+=("${boot_root}/$entry_token/${f##*/}")
	done
	extra=("${@/#/--extra=}")
	make_free_space "$snapshot" $((size / 1024 + 1)) || err "No free space in ${boot_root} for the UKI"

	local tries=""
	[ ! -f /etc/kernel/tries ] || read -r tries < /etc/kernel/tries
	[[ "$tries" =~ ^[0-9]+$ ]] || tries=""

	# "link" refuses an entry that is already there.  This is also
	# true for the entry of a profile ("@N").  So the old entries are
	# unlinked first.  If "unlink" fails, "link" says why
	local old
	for old in "${boot_root}/loader/entries/${id%.conf}"{.conf,[@+]*.conf}; do
		[ ! -e "$old" ] || bootctl_entries unlink "$(entry_key "${old##*/}").conf" || :
	done
	SYSTEMD_LOG_LEVEL=warning bootctl link "$uki" "${extra[@]}" \
		--entry-token="literal:$entry_token" --entry-commit="${snapshot:-1}" \
		--entry-version="${snapshot:+${snapshot}.}$kernel_version${variant:+.$variant}" \
		--entry-title="$title" ${tries:+--tries-left="$tries"} --keep-free=0 || \
		err "Cannot link the UKI of $kernel_version"

	# The new files come from here, so they can be part of a policy
	# (see `verify_esp_files`)
	for f in "${added[@]}"; do
		record_esp_file "$f"
	done

	# "link" takes the sort key from the os-release of the UKI.  That
	# sort key is the same for every snapshot, so it is replaced here
	entry="$(entry_file "$id")" || err "No entry $id after linking the UKI"
	sed -i "/^sort-key /d; \$a sort-key $sort_key" "$entry"

	rm -f "$tmpdir"/*.efi
	cleanup_pending=1
	update_predictions=1
}

# Stage the initrd of the kernel VERSION of SNAPSHOT (in SUBVOL) for a
# boot entry.  It is one of three: the initrd of the package (INITRD),
# the initrd of an entry that can be reused (in "dstinitrd", see
# `reuse_initrd`), or a new one made by dracut.  The first and the last
# end in "$tmpdir/initrd-0".  For a UKI (UKI not empty) it is always a
# new one.  This initrd knows nothing of the disks, like the initrd of
# a UKI of the packages.  It has no crypttab and no command line.  The
# addon of the root has them, when they are needed (see
# `update_dps_addon`)
stage_initrd()
{
	local snapshot="$1" subvol="$2" kernel_version="$3" initrd="$4" uki="${5:-}"

	if [ -e "$initrd" ]; then
		ln -sf "$initrd" "$tmpdir/initrd-0"
	elif [ -n "$uki" ] || ! reuse_initrd "$snapshot" "$subvol" "$kernel_version"; then
		local dracut_args=(
			'--reproducible'
			'--force'
			'--tmpdir' '/var/tmp'
		)
		if [ "${verbose:-0}" -le 1 ]; then
			dracut_args+=('--quiet')
		fi
		# The empty crypttab is in a directory.  This is because
		# "--include" does not replace a file that a module
		# installed.  It copies the content of a directory instead.
		# The path and the time are fixed, because dracut keeps
		# both in the initrd.  So the same content gives the same
		# initrd
		if [ -n "$uki" ]; then
			mkdir -p /var/lib/sdbootutil/uki-etc
			: > /var/lib/sdbootutil/uki-etc/crypttab
			touch -d "@$(signing_epoch)" /var/lib/sdbootutil/uki-etc/crypttab
			dracut_args+=('--no-hostonly-cmdline' '--include' /var/lib/sdbootutil/uki-etc '/etc')
		fi

		info "Generating new initrd"

		# When the running system is a mix of snapshots, the live
		# /usr is not the one of "$root_subvol".  So in that case the
		# initrd is always generated inside the snapshot
		if [ -n "$have_snapshots" ] && { [ "$subvol" != "$root_subvol" ] || [ -n "$applied_snapshot" ]; }; then
			mount_chroot "${subvol#"${subvol_prefix}"}"
			# In MicroOS the snapshot must have the same /etc.
			# For example, /etc/crypttab can have changes in
			# the overlay.  They are visible once the snapshot
			# is active.  But the version in /.snapshots is
			# still the unchanged base
			is_transactional && mount_etc "${subvol#"${subvol_prefix}"}"
			chroot "${subvol#"${subvol_prefix}"}" dracut "${dracut_args[@]}" "$tmpdir/initrd-0" "$kernel_version" \
				|| err "Failed to generate the initrd for $kernel_version"
			umount_chroot "${subvol#"${subvol_prefix}"}"
		else
			dracut "${dracut_args[@]}" "$tmpdir/initrd-0" "$kernel_version" \
				|| err "Failed to generate the initrd for $kernel_version"
		fi
	fi
}

install_kernel()
{
	local snapshot="$1"
	local subvol=""
	[ -z "$have_snapshots" ] || subvol="${subvol_prefix}/.snapshots/${snapshot}/snapshot"
	local kernel_version="$2"
	local dstinitrd=()
	local reused_entry=
	local src="${subvol#"${subvol_prefix}"}/lib/modules/$kernel_version/$image"
	[ -n "$kernel_version" ] || err "Missing kernel version"
	[ -e "$src" ] || err "Can't find $src"

	info "Installing kernel $kernel_version"
	dbg_var "snapshot"

	# The kernel packages install the kernel while the system is
	# still being installed.  At that point the installer has not
	# written "/etc/kernel/cmdline" yet.  An entry created now would
	# have a command line that is not the one of the installed
	# system.  Its initrd would come from a system that is not
	# configured yet.  So the installation is skipped.  The installer
	# calls "add-all-kernels" once the system is set up.  An empty
	# ESP tells this case apart from a configured system where the
	# administrator removed "/etc/kernel/cmdline"
	#
	# The subvolume is resolved like the one used later for the
	# options.  So both look at the same files
	local cmdline_subvol="$subvol"
	[ -z "$in_buildroot" ] || cmdline_subvol="${subvol_prefix}/.snapshots/${snapshot}/snapshot"
	[ -n "$arg_force" ] || kernel_cmdline_files "$cmdline_subvol" > /dev/null || ! no_boot_entries || {
		# Building an image is a single pass.  Nothing will install
		# the kernel later.  So a missing command line is a
		# configuration error, not a transient state
		[ -z "$in_buildroot" ] || err "No kernel command line configured for $kernel_version"
		warn "The system seems to be not fully configured (no kernel command line)"
		warn "Kernel $kernel_version will not be installed"
		return 0
	}

	[ -z "$TRANSACTIONAL_UPDATE" ] || [ -n "$arg_force" ] || {
		warn "Inside transactional-update. Installing kernels must be done outside the transaction"
		return 0
	}

	settle_entry_token "${snapshot}"

	update_dps_addon

	# A UKI entry is made only when the UKI can boot.  With Secure
	# Boot, its certificate has to be in MOK first.  Until then, the
	# entry has the kernel and the initrd
	if uki_selected; then
		uki_keys
		if is_secure_boot && [ "$(mok_state)" != "enrolled" ]; then
			mok_enroll
		elif [ "$UKI" = "local" ]; then
			install_local_uki "$snapshot" "$subvol" "$kernel_version" "$src"
			return 0
		elif install_distro_ukis "$snapshot" "$subvol" "$kernel_version"; then
			return 0
		fi
	fi

	# `find_kernels` already has the checksum when it ran for this
	# snapshot
	chksum=""
	[ "${found_kernels_snapshot-unset}" != "$snapshot" ] || chksum="${found_kernels[$kernel_version]:-}"
	[ -n "$chksum" ] || calc_chksum "$src"
	local dst="/$entry_token/$kernel_version/linux-$chksum"
	local devicetree_src=
	local devicetree_dst=

	local conf
	conf="$(find_conf_file "$kernel_version" "$snapshot")" || conf=
	[ -z "$conf" ] \
		|| ! entry_is_complete "$conf" "$dst" \
		|| [ -n "$arg_no_reuse_initrd" ] \
		|| [ -n "$arg_force" ] \
		|| {
		info "Kernel $kernel_version already in the ESP"
		unlink_other_entries "$kernel_version" "$snapshot" "$(entry_conf_file "$kernel_version" "$snapshot")"
		return 0
	}

	local initrd="${src%/*}/initrd"

	# Resolve the device tree before creating any ESP directory.
	# When a configured blob is missing, the command aborts.  It
	# leaves no empty "$entry_token/$kernel_version" directory behind
	devicetree_src="$(resolve_devicetree_source "$subvol" "$kernel_version")" || err "Failed to resolve DEVICETREE_SOURCE"
	if [ -n "$devicetree_src" ]; then
		! is_secure_boot || err "External devicetree files are not supported when Secure Boot is enabled"
		calc_chksum "$devicetree_src"
		devicetree_dst="${dst%/*}/devicetree-$chksum.dtb"
	fi

	stage_initrd "$snapshot" "$subvol" "$kernel_version" "$initrd"

	# Files already in the ESP are reused.  They need no space
	local kernel_size_src="$src" devicetree_size_src="$devicetree_src"
	[ ! -e "${boot_root}$dst" ] || kernel_size_src=
	[ -z "$devicetree_dst" ] || [ ! -e "${boot_root}$devicetree_dst" ] || devicetree_size_src=
	make_free_space_for_kernel "$snapshot" "$kernel_size_src" "$tmpdir" "$devicetree_size_src" "${dst%/*}" || err "No free space in ${boot_root} for new kernel"

	local boot_options
	[ -z "$in_buildroot" ] || subvol="${subvol_prefix}/.snapshots/${snapshot}/snapshot"
	boot_options="$(create_boot_options "$subvol")"

	if [ "${#dstinitrd[@]}" -eq 0 ] && [ -e "$tmpdir/initrd-0" ]; then
		i=0
		while [ -e "$tmpdir/initrd-$i" ]; do
			calc_chksum "$tmpdir/initrd-$i"
			dstinitrd+=("${dst%/*}/initrd-$chksum")
			((++i))
		done
	fi

	# A boot entry without an initrd will not boot.  This can only
	# happen if the initrd generation failed where `set -e` does not
	# apply, like in a command substitution
	[ "${#dstinitrd[@]}" -ne 0 ] || err "No initrd found for $kernel_version in snapshot $snapshot"

	local title sort_key
	entry_title_and_sort_key title sort_key "$snapshot" "$subvol" "$kernel_version"

	local entry_machine_id=
	[ "$entry_token" = "$machine_id" ] && entry_machine_id="$machine_id"

	# The snapshot number goes in front of the kernel version.  So
	# the boot loader sorts the entries by snapshot first.  The
	# separator is "_".  `strverscmp_improved()` drops it as a plain
	# segment separator.  It does the same with "@", the separator
	# used before, so both sort the same way.  "@" is outside the
	# UAPI.10 charset, and systemd v262 warns about it on every entry
	# it parses.  Entries written with "@" are still on disk, and
	# every reader accepts both
	cat > "$tmpdir/entry.conf" <<-EOF
	# Boot Loader Specification type#1 entry
	title      $title
	version    ${snapshot:+${snapshot}_}$kernel_version${entry_machine_id:+${nl}machine-id $entry_machine_id}${sort_key:+${nl}sort-key   $sort_key}
	options    $boot_options
	linux      $dst${devicetree_dst:+${nl}devicetree ${devicetree_dst}}
	EOF
	for i in "${dstinitrd[@]}"; do
		echo "initrd     $i" >> "$tmpdir/entry.conf"
	done
	# A repair only writes back the files that went missing.  The
	# rest of the entry stays as it was
	[ -z "$keep_entry_conf" ] || keep_entry_fields "$tmpdir/entry.conf"

	dbg "Generated new boot entry"
	dbg_cat "$tmpdir/entry.conf"

	mkdir -p "${boot_root}${dst%/*}"

	local failed=
	if [ ! -e "${boot_root}$dst" ]; then
		install_with_rollback "$src" "${boot_root}$dst" || failed=kernel
	else
		info "Reusing ${boot_root}$dst"
	fi
	if [ -z "$failed" ] && [ -n "$devicetree_src" ]; then
		if [ ! -e "${boot_root}${devicetree_dst}" ]; then
			install_with_rollback "$devicetree_src" "${boot_root}${devicetree_dst}" || failed=devicetree
		else
			info "Reusing ${boot_root}${devicetree_dst}"
		fi
	fi
	if [ -z "$failed" ] && [ -e "$tmpdir/initrd-0" ]; then
		i=0
		while [ -e "$tmpdir/initrd-$i" ]; do
			if [ ! -e "${boot_root}${dstinitrd[$i]}" ]; then
				install_with_rollback "$tmpdir/initrd-$i" "${boot_root}${dstinitrd[$i]}" || { failed=initrd; break; }
			fi
			((++i))
		done
	fi
	# Remove the staged initrds, also the ones that were in the ESP
	# already.  The next kernel stages its own
	rm -f "$tmpdir"/initrd-[0-9]*
	if [ -z "$failed" ]; then
		local tries=""
		[ ! -f /etc/kernel/tries ] || read -r tries < /etc/kernel/tries
		[[ "$tries" =~ ^[0-9]+$ ]] || tries=""

		# The directory can be missing if the user removed it, or
		# if the kernel is installed before the boot loader.
		# `find` fails when the directory is not there, and
		# `install` does not create it
		mkdir -p "${boot_root}/loader/entries"

		# The entry can be there already, with or without a boot
		# counter.  It is replaced by a file with the counter of
		# /etc/kernel/tries.  This avoids a duplicate
		local loader_entry loader_entry_current
		loader_entry="${boot_root}/loader/entries/$(entry_conf_file "$kernel_version" "$snapshot" "$tries")"
		loader_entry_current="$(entry_file "$(entry_conf_file "$kernel_version" "$snapshot")")" || loader_entry_current=""
		install_with_rollback "$tmpdir/entry.conf" "$loader_entry" "$loader_entry_current" || failed="bootloader entry"
		rm -f "$tmpdir/entry.conf"
	fi
	[ -z "$failed" ] || err "Failed to install $failed"
	reset_rollback
	unlink_other_entries "$kernel_version" "$snapshot" "$(entry_conf_file "$kernel_version" "$snapshot")"

	# A replaced initrd is left in the ESP, see `bootctl_cleanup`
	cleanup_pending=1

	update_predictions=1
}

install_all_kernels()
{
	local snapshot="$1"

	info "Installing all kernels"
	dbg_var "snapshot"
	dbg_var "arg_no_reuse_initrd"

	[ -z "$TRANSACTIONAL_UPDATE" ] || [ -n "$arg_force" ] || {
		warn "Inside transactional-update. Installing kernels / initrds must be done outside the transaction"
		return 0
	}

	find_kernels "$snapshot"
	for kv in "${!found_kernels[@]}"; do
		install_kernel "${snapshot}" "$kv"
	done
}

remove_all_kernels()
{
	local snapshot="$1"

	info "Removing all kernels"
	dbg_var "snapshot"

	[ -z "$TRANSACTIONAL_UPDATE" ] || [ -n "$arg_force" ] || {
		warn "Inside transactional-update. Removing kernels must be done outside the transaction"
		return 0
	}

	find_kernels "$snapshot"
	for kv in "${!found_kernels[@]}"; do
		remove_kernel "${snapshot}" "$kv"
	done
}

cleanup_entries()
{
	local snapshot="$1"

	info "Cleaning up boot entries"

	[ -z "$TRANSACTIONAL_UPDATE" ] || [ -n "$arg_force" ] || {
		warn "Inside transactional-update. Cleaning up boot entries must be done outside the transaction"
		return 0
	}

	if [ ! -s "$entryfile" ]; then
		update_entries_for_snapshot "$snapshot"
	fi

	local id path snapshot kernel_version subvol src
	while read -r id; do
		read -r path
		read -r snapshot
		read -r kernel_version
		subvol=
		if [ -n "$snapshot" ] && [ "$snapshot" != "null" ]; then
			subvol="${subvol_prefix}/.snapshots/${snapshot}/snapshot"
		fi
		src="${subvol#"${subvol_prefix}"}/lib/modules/$kernel_version/$image"
		[ -e "$src" ] || {
			info "Cleaning boot entry $id"
			rm "$path"
		}
	done < <(jq -r --arg snapshots "$have_snapshots" \
		    "$jq_entry_version"'.[] | .id, .path, (entry_version | .snapshot, .kernel)' "$entryfile")

	# The loop above drops an entry when its kernel is gone.  The
	# opposite case also happens: the kernel is still there, but
	# its copy in the ESP went missing.  That entry stops at the
	# firmware, and nothing repairs it.  Every other command gets a
	# single snapshot and only looks at that one.  This loop is the
	# only place that sees the whole system.
	#
	# Writing a kernel back means generating an initrd.  This is
	# slow and needs space in the ESP.  So it is done only when
	# asked for
	[ -z "$arg_repair" ] || {
		# The dangling entries are collected before the first
		# repair, not read one by one.  An entry deleted above is
		# still listed in "$entryfile", and `install_kernel`
		# rewrites that same file
		local dangling missing
		dangling="$(dangling_entries < "$entryfile")"
		[ -z "$dangling" ] || while IFS='|' read -r id path snapshot kernel_version missing; do
			info "Repairing boot entry $id, missing $missing"
			# The repair keeps what the entry says.  Only the
			# files it names are written again.  `install_kernel`
			# builds the new entry aside, and then replaces this
			# one.  So this entry stays readable meanwhile
			keep_entry_conf="$path"
			install_kernel "${snapshot:-$root_snapshot}" "$kernel_version"
			keep_entry_conf=
		done <<<"$dangling"
	}

	bootctl_cleanup

	# Guarantee ESP_FREE_SPACE.  Failing to reach it is not an
	# error here, because nothing is going to be installed
	make_free_space "${1:-$root_snapshot}" "0" || warn "Can't free space in ${boot_root}"
}

list_entries()
{
	local snapshot="$1"

	info "Listing boot entries"

	if [ ! -s "$entryfile" ]; then
		if [ -n "$snapshot" ]; then
			update_entries_for_snapshot "$snapshot"
		elif [ -n "$arg_all_entries" ]; then
			update_entries
		else
			update_entries_for_this_system
		fi
	fi

	# `bootctl` sets "isSelected" when the entry ID matches
	# "LoaderEntrySelected".  But grub2-bls writes this variable
	# differently, so nothing matches and "isSelected" is always
	# null.  So the entry is also compared here, through
	# `entry_key`, until grub2-bls is fixed
	local selected=
	[ -z "$interactive" ] || selected="$(entry_key "$(bli_efi_var_get "LoaderEntrySelected")")"

	local isdefault isselected isreported type id root conf title marker booted
	while read -r isdefault isselected isreported type id root conf title; do
		color=
		if [ "$isdefault" = "true" ]; then
			color="$color_bu"
		elif [ -n "$arg_only_default" ]; then
			continue
		fi
		# The entry that the boot loader reported as booted is
		# not always the default one.  So both are marked
		# separately.  The marker is kept out of the highlight, as
		# `list_snapshots` does
		marker=
		if [ -n "$interactive" ]; then
			booted=
			if [ "$isselected" = "true" ] || [ "${id%.conf}" = "$selected" ]; then
				booted=1
			fi
			if [ "$isdefault" = "true" ]; then
				marker="+"
				[ -z "$booted" ] || marker="*"
			elif [ -n "$booted" ]; then
				marker="-"
			fi
		fi
		if [ "$isreported" = "false" ]; then
			color="$color${color_green}"
		fi
		if [ "$type" = "loader" ]; then
			color="$color${color_yellow}"
		fi

		local errors=()
		if [ -n "$verbose" ] && [ -n "$conf" ]; then
			local v
			while read -r v; do
				if [ ! -e "$root$v" ]; then
					errors+=("$root/$v does not exist")
				fi
			done < <(entry_files "$conf")
			local snapshot
			while [ -n "$have_snapshots" ] && read -r v; do
				# shellcheck disable=SC2001
				snapshot="$(echo "$v" | sed -e "s,.*rootflags=subvol=${subvol_prefix}/.snapshots/\([0-9]\+\)/snapshot.*,\1,")"
				if [ ! -d "/.snapshots/$snapshot/snapshot" ]; then
					errors+=("/.snapshot/$snapshot/snapshot does not exist")
				fi
			done < <(entry_field "$conf" options)
		fi
		if [ "${#errors[@]}" -gt 0 ]; then
			echo -e "  ${color_red}${errors[*]}${color_end}" >&2
		fi
		echo -e "$marker$color$id${verbose:+: $title}${color:+$color_end}"
	done < <(jq '.[]|[.isDefault, .isSelected // false, if has("isReported") then .isReported else 0 end, if has("type") then .type else "unknown" end, .id, .root, .path, .showTitle]|join(" ")' -r < "$entryfile")
}

show_entry_fields()
{
	local snapshot="$1"
	local kernel_version="$2"
	[ -n "$kernel_version" ] || err "Missing kernel version"
	settle_entry_token "${snapshot}"
	local id
	id="$(entry_conf_file "$kernel_version" "$snapshot")"

	local conf
	# The status is collected here.  Else `set -e` ends the
	# script with an empty message when there is no entry for the
	# kernel.  When there is no entry of the kernel and the
	# initrd, the entry of its UKI is used
	if ! conf="$(find_conf_file "$kernel_version" "$snapshot")"; then
		id="$(linked_entry_ids "$kernel_version" "$snapshot" | head -n 1)"
		conf="$(entry_file "${id:-none}")" || err "Missing boot entry for kernel $kernel_version"
	fi

	[ -z "$verbose" ] || echo -e "ID\t$id"
	local k
	local v
	while read -r k v; do
		case "$k" in
			title|version|sort-key|options|linux|initrd|devicetree|uki|extra) ;;
			*) continue ;;
		esac

		if [ "${#arg_entry_keys[@]}" -eq 0 ] || [[ " ${arg_entry_keys[*]} " == *" all "* ]] || [[ " ${arg_entry_keys[*]} " == *" $k "* ]]; then
			echo -e "$k\t$v"
		fi
	done < <(entry_fields "$conf")
}

update_entry_conf()
{
	local conf="$1"
	local snapshot="$2"

	local subvol=""
	[ -z "$have_snapshots" ] || subvol="${subvol_prefix}/.snapshots/${snapshot}/snapshot"

	local boot_options
	boot_options="$(create_boot_options "$subvol")"

	# The first "options" line gets the new options.  The other
	# "options" lines are dropped, as they would add the old options
	# again.  sed is not used, because the options can have "&" or "|"
	local line found=
	while IFS= read -r line || [ -n "$line" ]; do
		if [[ "$line" =~ ^options([[:space:]]|$) ]]; then
			[ -z "$found" ] || continue
			found=1
			line="options    $boot_options"
		fi
		echo "$line"
	done < "$conf" > "$tmpdir/entry.conf"
	cp "$tmpdir/entry.conf" "$conf"
}

update_entry()
{
	local snapshot="$1"
	local kernel_version="$2"
	[ -n "$kernel_version" ] || err "Missing kernel version"

	settle_entry_token "${snapshot}"
	local id
	id="$(entry_conf_file "$kernel_version" "$snapshot")"

	local conf
	# A missing entry is not an error.  But `set -e` would end
	# the script before the check below
	#
	# The options of a UKI are in the addon of its entry.  The
	# addon is made again when the kernel is installed.  The entry
	# of the kernel and the initrd can still be there too.  This is
	# because the booted entry is kept after a switch to the UKIs
	if uki_selected && [ -n "$(linked_entry_ids "$kernel_version" "$snapshot")" ]; then
		install_kernel "$snapshot" "$kernel_version"
	fi
	conf="$(find_conf_file "$kernel_version" "$snapshot")" || :
	[ -f "$conf" ] || return 0

	info "Updating boot entry $id"

	[ -z "$TRANSACTIONAL_UPDATE" ] || [ -n "$arg_force" ] || {
		warn "Inside transactional-update. Updating boot entries must be done outside the transaction"
		return 0
	}

	update_entry_conf "$conf" "$snapshot"

	update_predictions=1
}

update_all_entries()
{
	local snapshot="$1"

	info "Updating all boot entries"

	settle_entry_token "${snapshot}"

	[ -z "$TRANSACTIONAL_UPDATE" ] || [ -n "$arg_force" ] || {
		warn "Inside transactional-update. Updating boot entries must be done outside the transaction"
		return 0
	}

	make_free_space "$snapshot" 1024 || warn "Can't free space in ${boot_root}"

	update_entries_for_snapshot "$snapshot"

	while read -r conf; do
		update_entry_conf "$conf" "$snapshot"
	done < <(jq -r '.[]|.path' < "$entryfile")

	# The options of a UKI are in the addon of its entry.  The
	# addon is made again when the kernel is installed
	if uki_selected; then
		local kv
		find_kernels "$snapshot"
		for kv in "${!found_kernels[@]}"; do
			[ -z "$(linked_entry_ids "$kv" "$snapshot")" ] || install_kernel "$snapshot" "$kv"
		done
	fi

	update_predictions=1
}

list_snapshots()
{
	[ -n "$have_snapshots"  ] || { info "System does not support snapshots."; return 0; }
	[ -s "$snapperfile" ] || update_snapper 2>"$tmpfile" || err "$(cat "$tmpfile")"

	info "Listing snapshots"

	local n=0
	local marker
	while read -r n isdefault title; do
		[ "$n" != "0" ] || continue
		local id="$n"
		if [ "$isdefault" = "true" ]; then
			id="$color_bu$id$color_end"
		fi
		update_kernels "$n"
		[ "$is_bootable" = 1 ] || id="!$id"
		# The snapshot that the system runs from is not always
		# the default one.  So both are marked separately
		marker=
		if [ -n "$interactive" ]; then
			if [ "$isdefault" = "true" ]; then
				marker="+"
				[ "$n" != "$running_snapshot" ] || marker="*"
			elif [ "$n" = "$running_snapshot" ]; then
				marker="-"
			fi
		fi
		echo -e "$marker$id $title"
	done < <(jq '.root|.[]|[.number, .default, .description]|join(" ")' -r < "$snapperfile")
}

calc_chksum()
{
	# shellcheck disable=SC2046
	set -- $(sha1sum "$1")
	chksum="$1"
}

# Map with the kernel version as key and its checksum as value
declare -A found_kernels
find_kernels()
{
	local subvol=""
	[ -z "$have_snapshots" ] || subvol="${subvol_prefix}/.snapshots/${1:?}/snapshot"
	local fn kv
	found_kernels=()
	found_kernels_snapshot="${1:-}"

	for fn in "${subvol#"${subvol_prefix}"}"/usr/lib/modules/*/"$image"; do
		kv="${fn%/*}"
		kv="${kv##*/}"
		calc_chksum "$fn"
		found_kernels["$kv"]="$chksum"
		info "Found kernel $kv = $chksum"
	done
}

# Set by `install_kernel` and `link_uki`.  The files of a replaced
# entry can be left in the ESP.  `bootctl_cleanup` runs once at the
# end to remove them
cleanup_pending=

# Map with the expected ESP path of each installed kernel as key.
# The value is the entry id, if an entry exists
declare -A installed_kernels
# Map with the ESP path of each kernel that is not in the subvolume
# as key, and the entry id as value
declare -A stale_kernels
is_bootable=
update_kernels()
{
	local snapshot="$1"
	local path id
	installed_kernels=()
	stale_kernels=()
	is_bootable=
	find_kernels "$snapshot"
	settle_entry_token "${snapshot}"
	for kv in "${!found_kernels[@]}"; do
		installed_kernels["/$entry_token/$kv/linux-${found_kernels[$kv]}"]=''
	done
	update_entries_for_snapshot "$snapshot"

	# XXX: maybe we should parse the actual path in the entry
	while read -r path id; do
		if [ "${installed_kernels[$path]+none}" = 'none' ]; then
			installed_kernels["$path"]="$id"
			is_bootable=1
		else
			# A kernel in the ESP that is not installed
			stale_kernels["$path"]="$id"
		fi
	done < <(jq -r '.[]|select(has("linux"))|[.linux,.id]|join(" ")'< "$entryfile")
}

list_kernels()
{
	local snapshot=""
	[ -z "$have_snapshots" ] || snapshot="${1:?}"

	info "Listing kernels"

	update_kernels "$snapshot"
	local kernelfiles=("${!installed_kernels[@]}")
	for k in "${kernelfiles[@]}"; do
		local id="${installed_kernels[$k]}"
		local kv="${k%/*}"
		kv="${kv##*/}"
		if [ -z "$id" ]; then
			echo -e "${color_yellow}missing /lib/modules/$kv/$image${color_end}"
		else
			echo -e "${color_green}ok /lib/modules/$kv/$image -> $id${color_end}"
		fi
	done
	kernelfiles=("${!stale_kernels[@]}")
	for k in "${kernelfiles[@]}"; do
		local id="${stale_kernels[$k]}"
		printf "${color_red}stale %s${color_end}\n" "$id"
	done
}

list_devices()
{
	info "Listing devices"

	detect_tracked_devices || return 0

	for dev in "${tracked_devices[@]}"; do
		echo "$dev"
	done
}

is_shim_installed()
{
	# Check if shim is installed in the ESP.  An installed system
	# has a shim.efi
	[ ! -f "${esp_root}${esp_dst}/shim.efi" ] || return 0
	# Removable media has only BOOT${arch}.EFI
	! grep -q "UEFI SHIM" "${esp_root}/EFI/BOOT/BOOT${firmware_arch^^}.EFI" 2> /dev/null || return 0
	return 1
}

is_bootable()
{
	local snapshot="$1"
	update_kernels "$snapshot"

	[ "$is_bootable" = 1 ] || return 1
	return 0
}

shim_version()
{
	local fn="$1"
	if [ -z "$1" ]; then
		is_shim_installed || return 1
		if [ -n "$arg_portable" ]; then
			fn="${esp_root}/EFI/BOOT/BOOT${firmware_arch^^}.EFI"
		else
			fn="${esp_root}${esp_dst}/shim.efi"
		fi
	fi
	[ -e "$fn" ] || return 1

	# The version alone does not help, as it has only major.minor.
	# So the time of the last update is appended, down to the
	# minutes.  Not seconds, because FAT stores dates differently
	# than other file systems
	local v
	# The leading `$` is a literal.  grep reads it as a literal only
	# when it is escaped
	# shellcheck disable=SC2016
	read -r _ v _ < <(grep -ao '\$Version: [^$]\+ \$' "$fn")
	[ -n "$v" ] || return 1
	v="$v-$(date -r "$fn" +'%Y%m%d%H%M')"

	dbg "Shim version $v"

	echo "$v"
}

# The boot loader as deployed in the ESP
deployed_bootloader()
{
	if is_shim_installed; then
		echo "${esp_root}${esp_dst}/grub.efi"
	elif [ -n "$arg_portable" ]; then
		echo "${esp_root}/EFI/BOOT/BOOT${firmware_arch^^}.EFI"
	else
		local bootloader
		bootloader="$(find_bootloader)"
		echo "${esp_root}${esp_dst}/${bootloader##*/}"
	fi
}

bootloader_version()
{
	local fn="$1"
	[ -n "$fn" ] || fn="$(deployed_bootloader)"
	[ -e "$fn" ] || return 1
	if is_sdboot; then
		read -r _ _ _ v _ < <(grep -ao '#### LoaderInfo: systemd-boot [^#]\+ ####' "$fn")
	else
		# The version alone does not help, as it has only
		# major.minor.  So the time of the last update is appended,
		# down to the minutes.  Not seconds, because FAT stores
		# dates differently than other file systems
		read -r _ _ _ v _ < <(grep -aoP 'GNU GRUB  version %s\x00+[^\x00]+\x00' "$fn")
		v="${v:2}-$(date -r "$fn" +'%Y%m%d%H%M')"
	fi
	[ -n "$v" ] || return 1

	dbg "Bootloader version $v"

	echo "$v"
}

is_installed()
{
	info "Checking if the bootloader is installed"
	bootloader_version > /dev/null && [ -e "${esp_root}/${esp_dst}/installed_by_sdbootutil" ]
}

find_shim()
{
	local prefix=""
	[ -z "$have_snapshots" ] || prefix="/.snapshots/${1-$root_snapshot}/snapshot"
	echo "$prefix$shimdir/shim.efi"
}

find_sdboot()
{
	local prefix=""
	[ -z "$have_snapshots" ] || prefix="/.snapshots/${1-$root_snapshot}/snapshot"
	# XXX: this is a hack in case we need to inject a signed
	# systemd-boot from a separate package
	local sdboot="$prefix/usr/lib/systemd-boot/systemd-boot$firmware_arch.efi"
	[ -e "$sdboot" ] || sdboot="$prefix/usr/lib/systemd/boot/efi/systemd-boot$firmware_arch.efi"
	echo "$sdboot"
}

find_grub2_bls()
{
	local prefix=""
	[ -z "$have_snapshots" ] || prefix="/.snapshots/${1-$root_snapshot}/snapshot"

	local grub2_arch
	grub2_arch="$(uname -m)"
	case "$grub2_arch" in
		i[[3456]]86) grub2_arch=i386 ;;
		x86_64) grub2_arch=x86_64 ;;
		amd64) grub2_arch=x86_64 ;;
		sparc) grub2_arch=sparc64 ;;
		mipsel|mips64el) grub2_arch=mipsel ;;
		mips|mips64) grub2_arch=mips ;;
		arm*) grub2_arch=arm ;;
		aarch64*) grub2_arch=arm64 ;;
		loongarch64) grub2_arch=loongarch64 ;;
		riscv32*) grub2_arch=riscv32 ;;
		riscv64*) grub2_arch=riscv64 ;;
	esac

	# The old grub.efi has the BLS patches, but it cannot be used.
	# This is because the creation of the configuration file and the
	# installation of bli.mod were dropped too
	echo "$prefix/usr/share/grub2/${grub2_arch}-efi/grubbls.efi"
}

find_bootloader()
{
	if is_sdboot "${1-$root_snapshot}"; then
		find_sdboot "${1-$root_snapshot}"
	elif is_grub2_bls "${1-$root_snapshot}"; then
		find_grub2_bls "${1-$root_snapshot}"
	else
		err "Bootloader not detected"
	fi
}

shim_needs_update()
{
	local snapshot=""
	[ -z "$have_snapshots" ] || snapshot="${1-$root_snapshot}"

	info "Checking if shim needs update"

	local v nv
	# The status of the next commands is checked below.  So it must
	# be collected on the same line.  Else `set -e` ends the script
	# before the check, without any message
	v="$(shim_version)" || :
	[ -n "$v" ] || return 1
	info "Deployed shim version $v"
	nv="$(shim_version "$(find_shim "$snapshot")")" || :
	[ -n "$nv" ] || return 1
	info "System shim version $nv"
	local status=0
	# Only the exit status is wanted here.  The reason is the same as
	# in `bootloader_needs_update`
	systemd-analyze compare-versions "$v" "$nv" > /dev/null 2>&1 || status="$?"
	if [ "$status" = "11" ]; then
		info "shim is newer than system shim"
		return 2
	elif [ "$status" = "12" ]; then
		info "shim needs to be updated"
		return 0
	fi
	info "shim is already up-to-date"
	return 1
}

bootloader_needs_update()
{
	local prefix=""
	local snapshot=""
	if [ -n "$have_snapshots" ]; then
		snapshot="${1-$root_snapshot}"
		prefix="/.snapshots/${snapshot}/snapshot"
	fi

	info "Checking if bootloader needs update"

	local bldr_name
	local v nv
	# The status of the next commands is checked below.  So it must
	# be collected on the same line.  Else `set -e` ends the script
	# before the check, without any message
	v="$(bootloader_version)" || :
	[ -n "$v" ] || return 1
	info "Deployed version $v"
	nv="$(bootloader_version "$(find_bootloader "$snapshot")")" || :
	[ -n "$nv" ] || return 1
	info "System version $nv"
	local status=0
	# The comparison prints to stdout ("261.2 == 261.2").  Only the
	# exit status is wanted here.  transactional-update and weak-modules2
	# read our stdout through a pipe.  It also lands in the rpm scriptlet
	# output, where the bare line explains nothing
	systemd-analyze compare-versions "$v" "$nv" > /dev/null 2>&1 || status="$?"
	bldr_name=$(bootloader_name "$snapshot")
	if [ "$status" = "12" ]; then
		info "$bldr_name needs to be updated"
		return 0
	fi

	# The same version can be a different binary, for example a
	# package rebuilt with a patch, or re-signed.  It is installed as
	# it is, so the files are compared, as `install_extra_entries` does
	if [ "$status" = "0" ] && ! cmp -s "$(deployed_bootloader)" "$(find_bootloader "$snapshot")"; then
		info "$bldr_name has the same version, but a different binary"
		return 0
	fi

	# `install_bootloader` deploys shim and the boot loader together.
	# So a new shim alone is a reason to run it.  The check is here and
	# not in the caller, because both are one question: "is what the ESP
	# boots the same as what the system has"
	local shim_status=0
	shim_needs_update "$snapshot" || shim_status=$?
	[ "$shim_status" != "0" ] || return 0

	if [ "$status" = "11" ]; then
		info "$bldr_name is newer than system bootloader"
		return 2
	fi
	info "$bldr_name is already up-to-date"
	return "$shim_status"
}

esp_root_drive_partno_dseq()
{
	local blkpart drive disk_seq_min
	blkpart="$(findmnt -nvo SOURCE "$esp_root")"
	drive="${blkpart##*/}"
	lsblk -o NAME,PKNAME,PARTN,DISK-SEQ --json > "$devicefile"
	# Read the json file with all the devices.  Look recursively at
	# the children for the partition of the ESP.  When it is found,
	# print its partition number and the (kernel) name of its parent.
	#
	# DISK-SEQ is used to guess the order of the devices that GRUB2
	# sees at boot (hdX,partY).  For the kernel this value does not
	# always start with 0, but in GRUB2 it does.  So it is rebased on
	# the minimum value found
	disk_seq_min="$(jq -r '[.. | ."disk-seq"? | numbers] | min' < "$devicefile")"
	jq -r --arg name "$drive" --arg base "$disk_seq_min" \
	   'first(
	     .blockdevices[]
	     | recurse(.children[]?)
	     | select(.children? | arrays | map(.name == $name) | any)
	     | {
		 "partn": .children[] | select(.name == $name).partn | tostring,
		 "name": .name,
		 "pkname": .pkname,
		 "disk-seq": ."disk-seq" - ($base | tonumber) | tostring
	       })
	   | if .pkname then "/dev/" + .pkname + " " + .partn + " " + ."disk-seq" else "/dev/" + .name + " " + .partn + " " + ."disk-seq" end
	   ' < "$devicefile"
}

# Print the EFI binary (EFI=) and the boot entry (ENTRY=) of the
# entries.d file "conf", one per line.  The entry is printed only if
# there is one.  Nothing is printed when the files are not in "root".
# The lines are KEY=VALUE, with or without spaces around "=".  Blank
# lines and comments are skipped
extra_entry_files()
{
	local root="$1"
	local conf="$2"

	local -A keys=()
	local line key value
	while read -r line || [ -n "$line" ]; do
		[ -n "$line" ] && [[ "$line" != '#'* ]] || continue
		IFS="=" read -r key value <<< "$line"
		read -r key <<< "$key"
		read -r value <<< "$value"
		if [[ "$line" != *=* ]] || [ -z "$key" ]; then
			warn "Ignoring the line \"$line\" in ${conf#"$root"}"
			continue
		fi
		keys["$key"]="$value"
	done < "$conf"

	local efi="${keys[EFI]:-}"
	local entry="${keys[ENTRY]:-}"
	[ -n "$efi" ] || { warn "No EFI= in ${conf#"$root"}"; return 0; }
	[ -f "$root$efi" ] || { warn "Missing extra entry file $efi"; return 0; }
	[ -z "$entry" ] || [ -f "$root$entry" ] || { warn "Missing extra entry file $entry"; return 0; }

	echo "$efi"
	[ -z "$entry" ] || echo "$entry"
}

# Install the extra boot entries that other packages ask for in
# entries.d.  Remove the ones that are not asked for anymore.  The EFI
# binary goes to /EFI/extra, and the boot entry to /loader/entries
install_extra_entries()
{
	local snapshot="$1"

	local root=""
	[ -z "$have_snapshots" ] || root="/.snapshots/${snapshot}/snapshot"

	update_entries_for_extra

	# The files in the ESP that are asked for
	local -A installed=()

	local confs=()
	mapfile -t confs < <(uapi_files "$root" sdbootutil/entries.d "*.conf")

	local conf files efi entry efi_dst entry_dst
	for conf in "${confs[@]}"; do
		[ -f "$conf" ] && [ -s "$conf" ] || continue
		dbg_cat "$conf"

		files=()
		mapfile -t files < <(extra_entry_files "$root" "$conf")
		efi="${files[0]:-}"
		entry="${files[1]:-}"
		[ -n "$efi" ] || { warn "Skipping extra entry ${conf#"$root"}"; continue; }

		# Two files with the same destination would replace each
		# other in every run
		efi_dst="/EFI/extra/${efi##*/}"
		entry_dst="${entry:+/loader/entries/${entry##*/}}"
		if [ -n "${installed[$efi_dst]:-}" ] || { [ -n "$entry_dst" ] && [ -n "${installed[$entry_dst]:-}" ]; }; then
			warn "Skipping extra entry ${conf#"$root"}: $efi_dst${entry_dst:+ or $entry_dst} is already installed"
			continue
		fi
		installed["$efi_dst"]=1
		[ -z "$entry_dst" ] || installed["$entry_dst"]=1

		# The files are compared, not the version of the entry.  A
		# rebuild (a re-signed binary) has the same version.  A
		# downgrade has an older one
		cmp -s "$root$efi" "$esp_root$efi_dst" || install -p -D "$root$efi" "$esp_root$efi_dst"
		[ -z "$entry" ] || cmp -s "$root$entry" "$boot_root$entry_dst" || {
			install -p -D "$root$entry" "$boot_root$entry_dst"
			record_esp_file "$boot_root$entry_dst"
		}
	done

	# Remove the extra entries that are not asked for.  This includes
	# an entry whose name changed.  Then remove the EFI binaries that are
	# not asked for
	local path
	while read -r efi; do
		read -r path
		[ -n "${installed[$efi]:-}" ] && [ -n "${installed[/loader/entries/${path##*/}]:-}" ] || rm -f "$path"
	done < <(jq -r '.[] | .linux // .efi, .path' < "$entryfile")

	for efi in "${esp_root}"/EFI/extra/*; do
		[ -n "${installed[${efi#"${esp_root}"}]:-}" ] || rm -f "$efi"
	done

	update_predictions=1
}

install_bootloader()
{
	local snapshot=""
	local prefix=""
	if [ -n "$have_snapshots" ]; then
		snapshot="${1:-$root_snapshot}"
		# The binaries come from the same snapshot that
		# `bootloader_needs_update` checked.  It is not always the
		# running one
		prefix="/.snapshots/${snapshot}/snapshot"
	fi

	info "Installing bootloader"
	dbg_var "$snapshot"

	[ -z "$TRANSACTIONAL_UPDATE" ] || [ -n "$arg_force" ] || {
		warn "Inside transactional-update. Installing bootloader must be done outside the transaction"
		return 0
	}

	local bootloader bldr_name
	settle_entry_token "${snapshot}"

	bootloader=$(find_bootloader "$snapshot")
	bldr_name=$(bootloader_name "$snapshot")
	dbg_var "bootloader"
	dbg_var "bldr_name"

	mkdir -p "${esp_root}/loader"
	mkdir -p "${boot_root}/loader/entries"

	if [ -n "$arg_secure_boot" ] && [ ! -e "$prefix$shimdir/shim.efi" ]; then
		warn "A secure boot installation cannot be done. The shim package is not installed"
	fi

	if [ -n "$arg_secure_boot" ] && [ -e "$prefix$shimdir/shim.efi" ]; then
		info "Installing $bldr_name with shim into $esp_root"
		entry="$esp_dst/shim.efi"
		for i in MokManager shim; do
			[ -n "$arg_portable" ] || install -p -D "$prefix$shimdir/$i.efi" "${esp_root}${esp_dst}/$i.efi"
		done
		install -p -D "$bootloader" "${esp_root}${esp_dst}/grub.efi"

		# The default boot path of the firmware, /EFI/BOOT
		install -p -D "$prefix$shimdir/MokManager.efi" "${esp_root}/EFI/BOOT/MokManager.efi"
		[ -n "$arg_portable" ] || install -p -D "$prefix$shimdir/fallback.efi" "${esp_root}/EFI/BOOT/fallback.efi"
		install -p -D "$prefix$shimdir/shim.efi" "${esp_root}/EFI/BOOT/BOOT${firmware_arch^^}.EFI"
		[ -n "$arg_portable" ] || record_esp_file "${esp_root}${esp_dst}/shim.efi"
		record_esp_file "${esp_root}${esp_dst}/grub.efi"
	else
		info "Installing $bldr_name without shim into $esp_root"
		entry="$esp_dst/${bootloader##*/}"
		[ -n "$arg_portable" ] || install -p -D "$bootloader" "${esp_root}$entry"
		install -p -D "$bootloader" "${esp_root}/EFI/BOOT/BOOT${firmware_arch^^}.EFI"
		[ -n "$arg_portable" ] || record_esp_file "${esp_root}$entry"
	fi
	record_esp_file "${esp_root}/EFI/BOOT/BOOT${firmware_arch^^}.EFI"

	# shellcheck disable=SC2154
	[ -n "${os_release_NAME}" ] || set_os_release "${snapshot}"
	local split
	IFS=" " read -r -a split <<<"${os_release_NAME}"
	local boot_manager
	boot_manager="${split[0]} Boot Manager"

	# shim reads boot.csv to create the boot entry when it is missing
	[ -n "$arg_portable" ] || echo "${entry##*/},$boot_manager" | { echo -ne "\xff\xfe"; iconv -f ascii -t ucs-2le; } > "${esp_root}${esp_dst}/boot.csv"

	mkdir -p "${boot_root}/${entry_token}"
	echo "$entry_token" > "${esp_root}${esp_dst}/installed_by_sdbootutil"

	mkdir -p "/etc/kernel"
	[ -s /etc/kernel/entry-token ] || echo "$entry_token" > /etc/kernel/entry-token
	update_random_seed

	if is_sdboot "$snapshot"; then
		[ -e "${esp_root}/loader/loader.conf" ] || {
			echo -e "#timeout 3\n#console-mode keep\n" > "${esp_root}/loader/loader.conf"
			record_esp_file "${esp_root}/loader/loader.conf"
		}
		[ -s "${boot_root}/loader/entries.srel" ] || echo type1 > "${boot_root}/loader/entries.srel"
	fi

	# Create the boot menu entry if it does not exist
	if [ -z "$arg_no_variables" ] && [ -z "$arg_portable" ] && mountpoint -q "$esp_root"; then
		local drive partno
		read -r drive partno _ < <(esp_root_drive_partno_dseq)

		local escaped_entry="${entry//\//\\\\}"
		efibootmgr | grep -q "Boot.*${boot_manager}.*${escaped_entry}" || efibootmgr -q --create --disk "$drive" --part "$partno" --label "${boot_manager} ($bldr_name)" --loader "$entry" || true

		# Make it the first option.  A system that never booted
		# from disk can have no `BootOrder` at all
		local boot_order
		boot_order="$(efibootmgr | grep BootOrder)" || :
		boot_order="${boot_order#BootOrder: }"

		# There can be more than one match, for example a stale
		# entry of a previous installation.  `efibootmgr` expects a
		# single ID.  So take the first active one (the `*` marker).
		# The firmware never boots an inactive entry
		local boot_entry
		boot_entry="$(efibootmgr | grep -m1 "Boot[0-9A-Fa-f]\{4\}\*.*${boot_manager}.*${escaped_entry}")" || :
		# The ID is printed as `BootXXXX`
		boot_entry="${boot_entry:4:4}"

		[ -z "$boot_entry" ] || efibootmgr -q -D -o "$boot_entry${boot_order:+,$boot_order}" || true
	fi

	update_predictions=1
}

bootloader_update()
{
	local status=0

	info "Updating bootloader"

	[ -z "$TRANSACTIONAL_UPDATE" ] || [ -n "$arg_force" ] || {
		warn "Inside transactional-update. Updating bootloader must be done outside the transaction"
		return 0
	}

	bootloader_needs_update "${1:-$root_snapshot}" || status=$?
	if [ $status -eq 0 ]; then
		info "The bootloader needs to be updated"
		install_bootloader "${1:-$root_snapshot}"
	elif [ -n "$arg_sync" ] && [ $status -eq 2 ]; then
		info "The bootloader will be downgraded"
		install_bootloader "${1:-$root_snapshot}"
	fi

	install_extra_entries "${1:-$root_snapshot}"
	rewrite_old_entry_versions "${1:-$root_snapshot}"
}

# Entries written before the "N_" prefix have "N@" in their version.
# systemd >= v262 warns about the "@" every time it reads one.  This
# function writes "N_" in the entries of this system, once.  The boot
# loader sorts both forms the same way.  grub2-bls measures the entry
# files, so the new files are recorded, and the predictions are updated
rewrite_old_entry_versions()
{
	local snapshot="$1" f
	settle_entry_token "$snapshot"
	for f in "${boot_root}/loader/entries/${entry_token}-"*.conf; do
		[ -e "$f" ] || continue
		grep -qE '^version[[:space:]]+[0-9]+@' "$f" || continue
		info "Writing \"N_\" in the version of ${f##*/}"
		sed -i -E 's/^(version[[:space:]]+[0-9]+)@/\1_/' "$f"
		record_esp_file "$f"
		update_predictions=1
	done
}

# `bootctl random-seed` hashes fresh entropy together with the seed
# that is already in the ESP.  It also writes the "LoaderSystemToken"
# EFI variable.
update_random_seed()
{
	[ -z "$arg_no_random_seed" ] || return 0

	local extra=()
	[ -z "$arg_no_variables" ] && [ -z "$arg_portable" ] && mountpoint -q "$esp_root" || extra=("--no-variables")

	local output
	output="$(bootctl "${extra[@]}" random-seed 2>&1)" || \
		warn "Failed to update the random seed${output:+: $output}"
	return 0
}

has_efivars()
{
	[ -w /sys/firmware/efi/efivars ]
}

bli_efi_var_get()
{
	# BLI uses this vendor UUID
	local efi_var="/sys/firmware/efi/efivars/${1:?}-4a67b082-0a4c-41cf-b6c7-440b29bb8c4f"
	# The file has 4 bytes of attributes, then the value in UTF-16LE
	[ ! -e "$efi_var" ] || dd "if=$efi_var" bs=2 skip=2 status=none | tr -d '\0'
}

bli_efi_var_set()
{
	# BLI uses this vendor UUID
	local efi_var="/sys/firmware/efi/efivars/${1:?}-4a67b082-0a4c-41cf-b6c7-440b29bb8c4f"
	local value="${2:?}"
	has_efivars || return 1
	[ -e "$efi_var" ] && chattr -i "$efi_var"
	echo -ne "\x07\x00${value}\x00" | iconv -t UTF-16LE > "$efi_var"
	chattr +i "$efi_var"
}

bli_efi_var_unset()
{
	local efi_var="/sys/firmware/efi/efivars/${1:?}-4a67b082-0a4c-41cf-b6c7-440b29bb8c4f"
	[ -e "$efi_var" ] || return 0
	chattr -i "$efi_var"
	rm -f "$efi_var"
}

loader_conf_set()
{
	local key="${1:?}"
	local value="${2:?}"

	[ -e "${esp_root}/loader/loader.conf" ] || touch "${esp_root}/loader/loader.conf"

	if grep -q "^$key " "${esp_root}/loader/loader.conf"; then
		# "|" is the delimiter, because a value can contain a path
		sed -i -e "s|^$key .*|$key $value|" "${esp_root}/loader/loader.conf"
	else
		echo "$key $value" >> "${esp_root}/loader/loader.conf"
	fi
	record_esp_file "${esp_root}/loader/loader.conf"
}

loader_conf_unset()
{
	local key="${1:?}"
	[ ! -e "${esp_root}/loader/loader.conf" ] || sed -i -e "/^$key /d" "${esp_root}/loader/loader.conf"
	record_esp_file "${esp_root}/loader/loader.conf"
}

loader_conf_get()
{
	local key="${1:?}"
	if [ -e "${esp_root}/loader/loader.conf" ]; then
		IFS=' ' read -r key value < <(grep "^$key " "${esp_root}/loader/loader.conf")
		echo -n "$value"
	fi
}

grubenv_set()
{
	local key="${1:?}"
	local value="${2:?}"

	[ -e "${esp_root}${esp_dst}/grubenv" ] || touch "${esp_root}${esp_dst}/grubenv"

	grubenv="$(mktemp -t grubenv.XXXXXX)"
	echo "# GRUB Environment Block" > "$grubenv"
	while read -r line; do
		[[ "$line" == '#'* ]] && continue
		[[ "$line" == "$key"=* ]] && continue
		echo "$line" >> "$grubenv"
	done < "${esp_root}${esp_dst}/grubenv"
	echo "$key=$value" >> "$grubenv"

	# GRUB2 reads a block of exactly 1024 bytes.  What is not a
	# variable is padding.  Now one `printf` writes the whole
	# padding.  Before, the padding came from `seq 1 $filler`.  For
	# a full block `seq` printed nothing.  But `printf` writes its
	# format once when it has no arguments.  So a block that was
	# already full got a 1025th byte
	local filler
	filler=$((1024 - $(stat -c %s "$grubenv")))
	[ "$filler" -ge 0 ] || err "grubenv has no room left for $key"
	printf '%*s' "$filler" "" | tr ' ' '#' >> "$grubenv"

	mv "$grubenv" "${esp_root}${esp_dst}/grubenv"
	record_esp_file "${esp_root}${esp_dst}/grubenv"
}

grubenv_get()
{
	local key="${1:?}"

	if [ -e "${esp_root}${esp_dst}/grubenv" ]; then
		IFS='=' read -r key value < <(grep "^$key=" "${esp_root}${esp_dst}/grubenv")
		echo -n "$value"
	fi
}

# systemd-boot boots the default entry even when boot counting marked
# it as bad.  So a snapshot that never boots correctly is tried
# forever.  The preferred entry (systemd 260) works differently.  When
# it is bad, it is skipped.  Then the boot loader moves on to the first
# entry that is not marked as preferred
sdboot_has_preferred()
{
	local features
	features="$(od -An -t u8 -j 4 -N 8 /sys/firmware/efi/efivars/LoaderFeatures-4a67b082-0a4c-41cf-b6c7-440b29bb8c4f 2> /dev/null)" || return 1
	(( (features >> 19) & 1 ))
}

set_default_sdboot()
{
	local id="${1:?}"

	# The entry is set as the preferred one or as the default one,
	# never both.  A bad preferred entry is skipped, and then the
	# default entry is booted.  This happens even when the default
	# is the same bad entry
	local key="default" stale="preferred"
	if sdboot_has_preferred; then
		key="preferred"
		stale="default"
	fi

	if ! has_efivars || [ -n "$arg_no_variables" ]; then
		loader_conf_set "$key" "$id"
	elif ! bli_efi_var_set "LoaderEntry${key^}" "$id"; then
		warn "EFI variable LoaderEntry${key^} cannot be set.  Falling back to configuration file"
		loader_conf_set "$key" "$id"
	fi
	loader_conf_unset "$stale"
	[ -n "$arg_no_variables" ] || bli_efi_var_unset "LoaderEntry${stale^}"
}

set_default_grub2_bls()
{
	local id="${1:?}"
	if systemd-analyze compare-versions "$(bootloader_version)" "<" "2.13" || ! has_efivars || [ -n "$arg_no_variables" ]; then
		grubenv_set "default" "$id"
	elif ! bli_efi_var_set "LoaderEntryDefault" "$id"; then
		warn "EFI variable LoaderEntryDefault cannot be set.  Falling back to configuration file"
		grubenv_set "default" "$id"
	fi
}

get_top_entry_id()
{
	local snapshot="$1"

	update_entries_for_snapshot "$snapshot"

	mapfile -t ids < <(jq -r '.[]|.id' < "$entryfile")
	if [ -z "${ids[0]}" ]; then
		# A bootctl error does not mean that the ESP is empty
		bootctl_entries list --json=short > /dev/null || err "Cannot read the boot entries"
		info "No boot entries found, trying to create them..."
		# The callers read the id from stdout.  The user has to see
		# what the installation says (the MOK password), so it goes
		# to stderr
		install_all_kernels "$snapshot" >&2
		update_entries_for_snapshot "$snapshot"

		mapfile -t ids < <(jq -r '.[]|.id' < "$entryfile")
		if [ -z "${ids[0]}" ]; then
			err "snapshot $snapshot has no kernels"
		fi
	fi

	echo "${ids[0]}"
}

set_default_entry()
{
	local id="$1"
	# `get_top_entry_id` can install kernels.  Inside a command
	# substitution, `set -e` does not abort this shell.  So the
	# result needs to be validated
	[ -n "$1" ] || id=$(get_top_entry_id "$root_snapshot")
	[ -n "$id" ] || err "Can't determine the top boot entry for snapshot $root_snapshot"

	info "Setting default entry $id"

	[ -z "$TRANSACTIONAL_UPDATE" ] || [ -n "$arg_force" ] || {
		warn "Inside transactional-update. Setting default entries must be done outside the transaction"
		return 0
	}

	entry_file "$id" > /dev/null || err "Boot loader entry $id not found"
	if is_sdboot; then
		set_default_sdboot "$id"
	elif is_grub2_bls; then
		set_default_grub2_bls "$id"
	else
		err "Bootloader not detected"
	fi

	# Setting a different boot entry invalidates "$entryfile"
	rm -f "$entryfile"

	# The PCR predictions have to be updated
	update_predictions=1
}

get_default_bootctl()
{
	update_entries_for_this_system
	jq -r '.[] | select(.isDefault == true) | .id' < "$entryfile"
}

get_default_sdboot()
{
	local val
	if has_efivars && [ -z "$arg_no_variables" ]; then
		val="$(bli_efi_var_get "LoaderEntryPreferred")"
		[ -n "$val" ] || val="$(bli_efi_var_get "LoaderEntryDefault")"
	fi
	[ -n "$val" ] || val="$(loader_conf_get "preferred")"
	[ -n "$val" ] || val="$(loader_conf_get "default")"
	[ -n "$val" ] || val="$(get_default_bootctl)"
	[ -z "$val" ] || echo "$val"
}

get_default_grub2_bls()
{
	local val
	if has_efivars && [ -z "$arg_no_variables" ]; then
		val="$(bli_efi_var_get "LoaderEntryDefault")"
	fi
	[ -n "$val" ] || val="$(grubenv_get "default")"
	[ -n "$val" ] || val="$(get_default_bootctl)"
	[ -z "$val" ] || echo "$val"
}

get_default_entry()
{
	if is_sdboot; then
		get_default_sdboot
	elif is_grub2_bls; then
		get_default_grub2_bls
	else
		err "Bootloader not detected"
	fi
}

# The snapshot that the boot loader is going to boot.  This is not
# always the snapshot that snapper calls default.  snapper switches the
# btrfs default subvolume before it runs the plugin.  Then the plugin
# writes the entry that the boot loader reads.  Some events leave the
# two pointing at different snapshots, for good: an interruption
# between these two steps, a manual `btrfs subvolume set-default`, or
# an aborted rollback.  Nothing repairs it later, because every actor
# keeps reading the value that it wrote (bsc#1252227)
#
# Empty when no default is set, when the default entry is gone, or
# when the entry describes no snapshot.  This is the case of a system
# without snapshots, or of an entry that this script does not manage
default_entry_snapshot()
{
	local id
	id="$(get_default_entry 2> /dev/null)" || return 0
	[ -n "$id" ] || return 0

	update_entries_for_this_system
	entry_snapshot "$id" < "$entryfile"
}

# The snapshot that an entry describes.  The entry list is read from
# stdin.  Empty when the entry is not in the list, or when it describes
# no snapshot
entry_snapshot()
{
	local id="${1:?}"

	# The id can come without ".conf", or with a boot counter
	jq -r --arg id "$(entry_key "$id")" --arg snapshots "$have_snapshots" "$jq_entry_version"'.[]
		| select((.id // "" | sub("\\.conf$"; "") | sub("\\+[0-9]+(-[0-9]+)?$"; "")) == $id)
		| snapshot // empty'
}

# The snapshot that snapper reports as default.  This is the btrfs
# default subvolume
default_snapper_snapshot()
{
	[ -n "$have_snapshots" ] || return 0
	[ -s "$snapperfile" ] || update_snapper
	jq -r '.root[]|select(.default==true)|.number' "$snapperfile"
}

# Warn when the two defaults disagree.  Nothing repairs this on its
# own.  Each actor keeps reading the store that it wrote.  The machine
# goes on booting an entry that no tool calls the default.  This lasts
# until the next successful `set-default-snapshot` writes both again
#
# The repair is that same command, with the snapshot that the boot
# loader already boots.  The other direction is not safe.  It would
# point the boot loader at a snapshot whose entries may be the ones
# that failed to install
warn_default_snapshot_diverged()
{
	local esp snapper
	esp="$(default_entry_snapshot)"
	snapper="$(default_snapper_snapshot)"
	[ -n "$esp" ] && [ -n "$snapper" ] || return 0
	[ "$esp" != "$snapper" ] || return 0

	warn "The default boot entry boots snapshot $esp, but snapper and btrfs default to $snapper"
	warn "Run 'sdbootutil set-default-snapshot $esp' to align them"
}

set_timeout_sdboot()
{
	local timeout="${1:?}"
	# `bootctl set-timeout menu-hidden` writes "0", and
	# "menu-disabled" writes the full text.  In both cases the menu
	# is hidden.
	#
	# `bootctl set-timeout menu-force` writes 2^32-1 in the EFI
	# variable (bsc#1258944).  The fix needs to be backported
	[ "$timeout" = "0" ] && timeout="menu-disabled"
	[ "$timeout" = "-1" ] && timeout="menu-force"

	if ! has_efivars || [ -n "$arg_no_variables" ]; then
		loader_conf_set "timeout" "$timeout"
	elif ! bli_efi_var_set "LoaderConfigTimeout" "$timeout"; then
		warn "EFI variable LoaderConfigTimeout cannot be set.  Falling back to configuration file"
		loader_conf_set "timeout" "$timeout"
	fi
}

set_timeout_grub2_bls()
{
	local timeout="${1:?}"
	# `bootctl set-timeout menu-hidden` writes "0", and
	# "menu-disabled" writes the full text.  In both cases the menu
	# is hidden.
	#
	# `bootctl set-timeout menu-force` writes 2^32-1 in the EFI
	# variable (bsc#1258944).  The fix needs to be backported
	#
	# The values are mapped to the strings that grub2-bls accepts
	# with the downstream patch
	[ "$timeout" = "menu-disabled" ] && timeout="menu-hidden"
	[ "$timeout" = "0" ] && timeout="menu-hidden"
	[ "$timeout" = "-1" ] && timeout="menu-force"

	if systemd-analyze compare-versions "$(bootloader_version)" "<" "2.13" || ! has_efivars || [ -n "$arg_no_variables" ]; then
		[ "$timeout" = "menu-disabled" ] || [ "$timeout" = "menu-hidden" ] && timeout=0
		[ "$timeout" = "menu-force" ] && timeout=-1
		grubenv_set "timeout" "$timeout"
	elif ! bli_efi_var_set "LoaderConfigTimeout" "$timeout"; then
		warn "EFI variable LoaderConfigTimeout cannot be set.  Falling back to configuration file"
		[ "$timeout" = "menu-disabled" ] || [ "$timeout" = "menu-hidden" ] && timeout=0
		[ "$timeout" = "menu-force" ] && timeout=-1
		grubenv_set "timeout" "$timeout"
	fi
}

set_timeout()
{
	local timeout="${1:?}"
	info "Setting timeout $timeout"
	if is_sdboot; then
		set_timeout_sdboot "$timeout"
	elif is_grub2_bls; then
		set_timeout_grub2_bls "$timeout"
	else
		err "Bootloader not detected"
	fi

	# The PCR predictions have to be updated
	update_predictions=1
}

get_timeout_sdboot()
{
	local val
	if has_efivars && [ -z "$arg_no_variables" ]; then
		val="$(bli_efi_var_get "LoaderConfigTimeout")"
	fi
	[ -n "$val" ] || val="$(loader_conf_get "timeout")"
	[ "$val" = "menu-disabled" ] || [ "$val" = "menu-hidden" ] && val=0
	[ "$val" = 4294967295 ] || [ "$val" = "menu-force" ] && val=-1
	[ -z "$val" ] || echo "$val"
}

get_timeout_grub2_bls()
{
	local val
	if has_efivars && [ -z "$arg_no_variables" ]; then
		val="$(bli_efi_var_get "LoaderConfigTimeout")"
	fi
	[ -n "$val" ] || val="$(grubenv_get "timeout")"
	[ "$val" = "menu-disabled" ] || [ "$val" = "menu-hidden" ] && val=0
	[ "$val" = 4294967295 ] || [ "$val" = "menu-force" ] && val=-1
	[ -z "$val" ] || echo "$val"
}

get_timeout()
{
	if is_sdboot; then
		get_timeout_sdboot
	elif is_grub2_bls; then
		get_timeout_grub2_bls
	else
		err "Bootloader not detected"
	fi
}

print_loader_path()
{
	local loader_path
	loader_path="$(bootctl --print-loader-path 2> /dev/null)" && {
		echo "${loader_path}"
		return 0
	} || true

	# Otherwise, try each known file name of the loader
	local bootloader
	bootloader=$(find_bootloader "$snapshot")
	for i in "grub.efi" "${bootloader##*/}" "BOOT${firmware_arch^^}.EFI"; do
		if [ -e "${esp_root}${esp_dst}/$i" ]; then
			echo "${esp_root}${esp_dst}/$i"
			return 0
		fi
	done

	echo "No loader EFI binary path found"
	return 1
}

set_default_snapshot()
{
	[ -n "$have_snapshots" ] || {
		info "System does not support snapshots."
		# suse-module-tools calls `sdbootutil
		# set-default-snapshot` to set the top entry as the
		# default entry.  When the system does not support
		# snapshots, the top entry is set as the default, and
		# the function returns early
		set_default_entry
		return 0
	}
	local snapshot="${1:?}"
	local id

	info "Setting default snapshot $snapshot"

	[ -z "$TRANSACTIONAL_UPDATE" ] || [ -n "$arg_force" ] || {
		warn "Inside transactional-update. Setting default snapshots must be done outside the transaction"
		return 0
	}

	# `get_top_entry_id` can install kernels.  Inside a command
	# substitution, `set -e` does not abort this shell.  So the
	# result needs to be validated
	id="$(get_top_entry_id "$snapshot")"
	[ -n "$id" ] || err "Can't determine the top boot entry for snapshot $snapshot"
	set_default_entry "$id"

	# The boot loader does not use the default snapshot to select
	# the default boot entry.  It is synchronized here anyway, for
	# coherence.  This invalidates any previous "$snapperfile"
	#
	# snapper is not used here.  This avoids recursion, and no
	# plugin is triggered
	local subvolume_id
	read -r _ subvolume_id _ < <(btrfs subvolume list -o /.snapshots | grep "${subvol_prefix}/.snapshots/$snapshot/snapshot")
	btrfs subvolume set-default "${subvolume_id}" /.snapshots
	rm -f "$snapperfile"
}

have_pcrlock()
{
	command -v systemd-pcrlock > /dev/null || command -v /usr/lib/systemd/systemd-pcrlock > /dev/null
}

# The sha256 of the file "$1" into the variable named "$2".  Each file
# is read once per run.  The kernels and initrds are large, and both
# the prediction and `verify_esp_files` need them.  The cache key has
# the inode, the size and the mtime.  So a file rewritten during the
# run is read again
declare -gA file_digests
file_digest()
{
	local -n fd_digest="${2:?}"
	local fd_key fd_sum
	fd_key="$1:$(stat -c "%i:%s:%y" "$1")"
	if [ -z "${file_digests["$fd_key"]+set}" ]; then
		read -r fd_sum _ < <(sha256sum "$1")
		file_digests["$fd_key"]="$fd_sum"
	fi
	# shellcheck disable=SC2034  # nameref
	fd_digest="${file_digests["$fd_key"]}"
}

# `systemd-pcrlock VERB [ARGS...] --pcrlock=OUT FILE`, taken from a
# cache keyed by the digest of FILE when possible.  Measuring the
# kernel and the initrd means reading them again.  This is most of the
# time of a prediction, and they rarely change.  A measurement depends
# only on what is measured.  So the key is made of the content, the
# verb and its arguments, and the active PCR banks (one digest per
# bank)
pcrlock_cache=/var/lib/sdbootutil/pcrlock-cache
pcrlock_cache_id=
declare -gA pcrlock_cache_used
pcrlock_file()
{
	local verb="${1:?}" out="${2:?}" file="${3:?}"
	shift 3
	local digest key bank

	if [ -z "$pcrlock_cache_id" ]; then
		for bank in /sys/class/tpm/tpm0/pcr-*; do
			pcrlock_cache_id+="${bank##*/pcr-}+"
		done
	fi

	file_digest "$file" digest
	key="$verb${*:+-$*}-$pcrlock_cache_id-$digest"
	key="${key//[^a-zA-Z0-9.=+-]/_}"
	pcrlock_cache_used["$key"]=1
	if [ -s "$pcrlock_cache/$key" ]; then
		# The directory of the component can be gone, because
		# unenroll keeps the cache
		mkdir -p "${out%/*}"
		cp "$pcrlock_cache/$key" "$out"
		return 0
	fi
	pcrlock "$verb" "$@" --pcrlock="$out" "$file" || return
	mkdir -p "$pcrlock_cache"
	cp "$out" "$pcrlock_cache/$key"
}

# Only the measurements of the files of this prediction stay cached
prune_pcrlock_cache()
{
	local entry
	for entry in "$pcrlock_cache"/*; do
		[ -n "${pcrlock_cache_used["${entry##*/}"]+set}" ] || rm -f "$entry"
	done
}

have_pcr_oracle()
{
	command -v pcr-oracle > /dev/null
}

# Warnings that `systemd-pcrlock` emits, once per event log record,
# when the firmware pads the UEFI device paths stored in the log.  All
# of them come from building the description of the record.  This
# description is only used to display the log.  So neither the policy
# nor the predictions are affected by them
pcrlock_noise="^(Garbage after device path end|Device path too short|Device path size does not match|Device path element too short), ignoring\.$"

# Run a command without the descriptor of the run lock (`take_lock`).
# The lock belongs to the open file, so this shell keeps holding it.
# systemd-pcrlock runs in its own SELinux domain.  This domain cannot
# write the lock file, and systemd-pcrlock has no use for it
without_lock()
{
	if [ -n "${lock_fd:-}" ]; then
		"$@" {lock_fd}>&-
	else
		"$@"
	fi
}

pcrlock()
{
	dbg "systemd-pcrlock $*"
	local pcrlock_cmd="/usr/bin/systemd-pcrlock"
	command -v "$pcrlock_cmd" > /dev/null || pcrlock_cmd="/usr/lib/systemd/systemd-pcrlock"

	if [ -n "$verbose" ]; then
		SYSTEMD_LOG_LEVEL="${SYSTEMD_LOG_LEVEL:-warning}" without_lock "$pcrlock_cmd" "$@"
		return
	fi

	local status=0
	SYSTEMD_LOG_LEVEL="${SYSTEMD_LOG_LEVEL:-warning}" without_lock "$pcrlock_cmd" "$@" \
		2>"$tmpdir/pcrlock.err" || status=$?
	grep -Ev "$pcrlock_noise" "$tmpdir/pcrlock.err" >&2 || :
	rm -f "$tmpdir/pcrlock.err"

	return "$status"
}

# `systemd-pcrlock` refuses to generate a component when the event log
# does not replay to the current value of one of the PCRs of the
# component.  It checks all these PCRs, not only the ones that the
# policy is going to seal.  Two cases are routine.  One is PCR 7 when
# secure boot is disabled.  The other is PCR 0 under a firmware that
# does not log everything that it measures, like the vTPM of VMware
# Workstation.  Neither is a reason to stop.  `predict` drops a PCR
# that has no component, and `get_final_pcrs` reports it
pcrlock_lock()
{
	local err status=0
	err="$(pcrlock "$@" 2>&1)" || status=$?
	[ "$status" -eq 0 ] || dbg "No component for '$1': ${err:-exit $status}"
}

is_pcr_oracle()
{
	[ -e /etc/systemd/tpm2-pcr-public-key.pem ] && \
	    [ -e /etc/systemd/tpm2-pcr-private-key.pem ] && \
	    have_pcr_oracle
}

pcr_oracle_public_key()
{
	# The public key that pcr-oracle used to sign the PCR policy is
	# not removed when the package goes away.  pcr-oracle writes it
	# in /etc only.  The key in /run is the key of the booted UKI.
	# The key in /usr/lib is the key of the UKIs of the distribution
	[ -e /etc/systemd/tpm2-pcr-public-key.pem ] || return 1
	echo /etc/systemd/tpm2-pcr-public-key.pem
}

snapshot_ids_for_prediction()
{
	# Select the IDs of the snapshots that take part in the
	# prediction.  The order is important: the most relevant come
	# first

	# Without snapshots there is no snapper to ask.  Calling it
	# only prints "snapper: command not found" twice per run
	[ -n "$have_snapshots" ] || return 0

	# Load the list of snapshots from snapper
	[ -s "$snapperfile" ] || update_snapper

	# The running snapshot, the default entry, and the default and
	# active snapshots of snapper, in this order, without repeats.
	# What the boot loader is going to boot comes before what
	# snapper calls default.  In the ordinary case they are the
	# same snapshot, and this costs no slot.  When they disagree,
	# the boot loader decides which entry is measured.  Sealing the
	# other one seals a boot that never happens.  Then the machine
	# asks for the recovery key at boot, and no later update can
	# notice (bsc#1252227)
	local -A snapshots
	local -a snapshot_ids
	local id
	while read -r id; do
		[ -n "$id" ] && [ -z "${snapshots[$id]}" ] || continue
		snapshot_ids+=("$id")
		snapshots[$id]=1
	done < <(echo "$root_snapshot"
		 default_entry_snapshot
		 jq -r '.root[]|select(.default==true)|.number' "$snapperfile"
		 jq -r '.root[]|select(.active==true)|.number' "$snapperfile")

	if is_transactional && [ -e "${state_file}" ]; then
		# shellcheck disable=SC1090
		. "${state_file}"
		for id in $LAST_WORKING_SNAPSHOTS; do
			if [ "${#snapshots[@]}" -lt 3 ]; then
				[ -n "${snapshots[$id]}" ] || snapshot_ids+=("$id")
				snapshots[$id]=1
			fi
		done
	else
		while read -r id; do
			if [ "${#snapshots[@]}" -lt 3 ]; then
				[ -n "${snapshots[$id]}" ] || snapshot_ids+=("$id")
				snapshots[$id]=1
			fi
		done < <(jq -r '.root|sort_by(.date)[-2:]|reverse|.[]|.number' "$snapperfile")
	fi

	echo "${snapshot_ids[@]}"
}

select_entries_for_prediction()
{
	# The ids in the regex are ordered by relevance, but the
	# returned set is not.  So a "priority" field and a "kernel"
	# (version) field are added, to order the set
	local ids
	ids="$(snapshot_ids_for_prediction)"

	if [ -n "$have_snapshots" ]; then
		update_entries_for_snapshot "(?:${ids// /|})"
	else
		# There is no snapshot to select.  Asking for one
		# ("rootflags=subvol=/.snapshots//snapshot") matches no
		# entry at all.  Then the prediction would be done
		# without the kernel, the initrd and the command line.
		# And `systemd-pcrlock` drops the PCRs of those
		# components
		update_entries_for_this_system
	fi

	# Extend the entry file with a "priority" field and a "kernel"
	# field.  The priority comes from the ordered snapshot IDs.
	# The kernel field is the kernel version.  The text suffix
	# (-default, -slowroll) is removed, and it does not take part
	# in the ordering
	#
	# Expected order for prediction:
	#
	# MicroOS
	#   - The default snapshot usually has the top priority (0),
	#     then the active one (1).  `snapshot_ids_for_prediction`
	#     sets this order
	#   - The last working snapshots come after those.  Also set
	#     by `snapshot_ids_for_prediction`
	#   - When the snapshot has several kernels, the higher
	#     version comes first
	#
	# Tumbleweed
	#   - Same as MicroOS (`snapshot_ids_for_prediction`)
	#   - The newest snapshots come after those.  Also set by
	#     `snapshot_ids_for_prediction`
	#   - When the snapshot has several kernels, the higher
	#     version comes first
	#
	# Without snapshots
	#   - The version of the entry has no "N_" (or "N@") prefix.
	#     There is no snapshot to order by, so every entry has the
	#     same priority.  Only the kernel version separates them,
	#     the higher one first
	#
	local filter
	# $id, $ids and $kernel below are jq variables, bound by --arg
	# and by "as".  So the filter has to reach jq unexpanded
	# shellcheck disable=SC2016
	# The snapshot is in the version ("N_" or "N@").  For the
	# entries of "bootctl link" it is in the id ("-commit_N.").
	# The version of these entries is "<commit>.<snapshot>.<kernel>"
	if [ -n "$have_snapshots" ]; then
		filter="$jq_entry_version"'def priority(id): id as $id | $ids | split(" ") | index($id); map(([.version // "" | scan("(\\d+)\\.(\\d+)\\.(\\d+)-(\\d+)")] | first) as $kernel | . + {"priority": priority(snapshot), "kernel": (($kernel // []) | map(tonumber))})'
	else
		filter='map(([.version // "" | scan("(\\d+)\\.(\\d+)\\.(\\d+)-(\\d+)")] | first) as $kernel | . + {"priority": 0, "kernel": (($kernel // []) | map(tonumber))})'
	fi
	jq --arg ids "$ids" --arg snapshots "$have_snapshots" "$filter"' | sort_by(.priority, (.kernel | map(-.)))' < "$entryfile" > "${entryfile}.ext"
	mv "${entryfile}.ext" "$entryfile"

	# While the UKIs are selected, PCR 9 is out of the policy.  So
	# nothing would bind the initrd of an entry with a separate
	# kernel and initrd.  These entries are left out.  They still
	# boot, but ask for the password.  They stay until there is a
	# UKI entry.  Otherwise the next boot would have no prediction
	# at all
	if next_boot_uki; then
		jq 'map(select(.uki))' < "$entryfile" > "${entryfile}.uki"
		mv "${entryfile}.uki" "$entryfile"
	fi
	dbg "Added priority and kernel version to entry file (for prediction)"
	dbg_cat "$entryfile"
}

backup_initial_components()
{
	select_entries_for_prediction
	mv "$entryfile" "$initialentryfile"
	cp -a "${boot_root}/." "$tmpdir"
	[ "$esp_root" = "$boot_root" ] || cp -a "${esp_root}/." "$tmpdir"
}

parse_eventlog()
{
	[ "${#eventlog[@]}" -eq 0 ] || return 0

	# Read only the event log.  "log" also loads and matches every
	# component, and that is slow with many variations
	while read -r line; do
		eventlog["$line"]=1
	done < <(pcrlock cel --json=short | jq -r '.[].digests[]? | select(.hashAlg == "sha256") | .digest' | sort -u)
}

find_matching_variation()
{
	local component="$1"

	local hashes=()
	for variation in /var/lib/pcrlock.d/"$component".pcrlock.d/*.pcrlock; do
		mapfile -t hashes < <(jq -r '.records | .[] | .digests | .[] | select(.hashAlg == "sha256") | .digest' < "$variation")
		for h in "${hashes[@]}"; do
			[ "${eventlog["$h"]+_}" ] || continue 2
		done
		echo "$variation"
		break
	done
}

shift_component()
{
	local component="$1"

	dbg "Shifting component $component"
	[ -d "/var/lib/pcrlock.d/$component.pcrlock.d" ] || {
		dbg "The component is not a directory or is missing"
		return 0
	}
	parse_eventlog

	# Only the variation that matches the current event log is set
	# aside.  Keeping all the variations of a component would
	# increase the number of combinations, and reach the PolicyOR
	# limit early.  The component is generated again.
	# `restore_shifts` puts the variation back if it is not one of
	# the new variations
	local variation name
	variation="$(find_matching_variation "$component")"
	if [ -n "$variation" ]; then
		dbg "$variation found in the eventlog"
		name="${variation##*/}"
		mkdir -p "$tmpdir/shift/$component.pcrlock.d"
		# Copied, not moved.  The file is written again in
		# /var/lib/pcrlock.d, so it gets the label of the directory
		cp "$variation" "$tmpdir/shift/$component.pcrlock.d/shift-${name#shift-}"
	else
		dbg "No matching variation found for $component"
	fi
	# The old variations are removed in any case.  Otherwise the
	# variations of entries that are gone would stay in the policy
	rm -f /var/lib/pcrlock.d/"$component".pcrlock.d/*.pcrlock
}

# The maximum number of variations of the components that sdbootutil
# limits.  This keeps the PCRs that they measure inside the PolicyOR
# limit (see `get_final_pcrs`).  `restore_shifts` keeps the same limit
declare -gA variation_limit=(
	[650-kernel-efi-application]=4
	[710-kernel-cmdline-initrd-entry]=4
	[710-kernel-cmdline-boot-loader]=4
	[650-grub2-bls-entry-cmdline]=8
	[710-grub2-bls-kernel-initrd-kernel-cmdline-initrd-entry]=2
)

# `shift_component` sets aside the variation of the current boot.  It
# goes back as "shift-*", but only when none of the new variations is
# the same one.  In that case the next boot measures something else,
# and the policy has to accept this boot too.  So a shifted variation
# means "changed since the boot"
restore_shifts()
{
	local shifted dir variation component limit v n last
	for shifted in "$tmpdir"/shift/*.pcrlock.d/*.pcrlock; do
		dir="/var/lib/pcrlock.d/${shifted#"$tmpdir/shift/"}"
		dir="${dir%/*}"
		for variation in "$dir"/*.pcrlock; do
			! cmp -s "$shifted" "$variation" || continue 2
		done

		# When the component is full, its last variation is
		# removed, to make room for the current boot.  The
		# generators number the variations by priority
		# ("linux-1", "uki-2"...), so the last one is the least
		# important.  Without this, the PCR is dropped from the
		# policy
		component="${dir##*/}"
		limit="${variation_limit["${component%.pcrlock.d}"]:-}"
		if [ -n "$limit" ]; then
			local variations=("$dir"/*.pcrlock)
			if [ "${#variations[@]}" -ge "$limit" ]; then
				variation='' last=0
				for v in "${variations[@]}"; do
					n="${v%.pcrlock}"
					n="${n##*-}"
					[[ "$n" =~ ^[0-9]+$ ]] && [ "$n" -gt "$last" ] || continue
					variation="$v" last="$n"
				done
				dbg "Removing ${variation##*/} from $dir, to keep the current boot"
				rm -f "$variation"
			fi
		fi

		dbg "Keeping ${shifted##*/} for $dir, the current boot differs from the prediction"
		mkdir -p "$dir"
		cp "$shifted" "$dir/"
	done
	rm -rf "$tmpdir/shift"
}

uint64_le()
{
	# The 64 bit little endian form of a number, as escape
	# sequences for `echo -ne`.  Nothing measured here is big
	# enough to reach the high 32 bits
	local value="$1"

	printf '\\x%02x' \
	       "$((value & 255))" \
	       "$((value >> 8 & 255))" \
	       "$((value >> 16 & 255))" \
	       "$((value >> 24 & 255))" \
	       0 0 0 0
}

pcrlock_secureboot_sbatlevel()
{
	# shim measures the `SbatLevel` variable into PCR 7, as an
	# EV_EFI_VARIABLE_AUTHORITY event.  When Secure Boot is
	# enabled, `systemd-pcrlock lock-secureboot-authority` collects
	# every EV_EFI_VARIABLE_AUTHORITY record of PCR 7, in event log
	# order.  It does not filter by variable name.  So this
	# measurement is already covered, and there is nothing to do.
	# When Secure Boot is disabled, that command removes the
	# component and generates nothing.  Then no component owns the
	# shim measurement.  A measurement that no component claims
	# drops the whole PCR from the policy.  So PCR 7 could never be
	# sealed on a system that boots with shim but without Secure
	# Boot.
	#
	# The prediction is written under the name of the failing
	# verb, not under a new name.  `SbatLevel` is exactly the
	# record that `lock-secureboot-authority` would have claimed.
	# So its position in the replay order is correct.  If Secure
	# Boot is enabled later, the verb overwrites the file with the
	# complete set of authorities.  A component with a name of our
	# own would survive that change.  Then `SbatLevel` would be
	# replayed twice, and the PCR that it should fix would break
	local component_dir=/var/lib/pcrlock.d/620-secureboot-authority.pcrlock.d

	! is_secure_boot || {
		dbg "Secure Boot enabled, SbatLevel is locked by lock-secureboot-authority"
		return 0
	}

	local guid="605dab50-e046-4300-abb6-3dd810dd8b23"
	# The same GUID in binary form.  The first three fields are
	# stored in little endian.  The last two are stored as they
	# are written
	local guid_le='\x50\xab\x5d\x60\x46\xe0\x00\x43\xab\xb6\x3d\xd8\x10\xdd\x8b\x23'

	# The variable is measured as `SbatLevel`.  At runtime it is
	# exposed as `SbatLevelRT`
	local name="SbatLevel"
	local var="/sys/firmware/efi/efivars/${name}RT-$guid"

	# Without shim there is no `SbatLevel` measurement to claim.
	# And `lock-secureboot-authority` already removed the component
	[ -e "$var" ] || {
		dbg "Missing $var, skipping the SbatLevel component"
		return 0
	}

	# The measured data is a UEFI_VARIABLE_DATA structure.  It has
	# the GUID, the length of the name in characters, the length of
	# the content in bytes, the name in UTF-16LE, and the content.
	# The first four bytes of the efivarfs file are the
	# attributes.  They are not part of the variable content
	local size
	size="$(stat -c%s "$var")"
	size=$((size - 4))

	{
		echo -ne "$guid_le$(uint64_le "${#name}")$(uint64_le "$size")"
		echo -n "$name" | iconv -t UTF-16LE
		tail -c "$size" "$var"
	} > "$tmpdir/sbatlevel"

	mkdir -p "$component_dir"
	pcrlock \
		lock-raw \
		--pcr=7 \
		--pcrlock="$component_dir/generated.pcrlock" \
		"$tmpdir/sbatlevel"
	rm "$tmpdir/sbatlevel"
	dbg_cat "$component_dir/generated.pcrlock"
}

pcrlock_cmdline_initrd()
{
	local cmdline="$1"
	local initrd="$2"
	local suffix="$3"

	# 710-kernel-cmdline-initrd-entry.pcrlock.d is not part of the
	# pcrlock standards
	echo -n "$cmdline" > "$tmpdir/cmdline"
	pcrlock \
		lock-kernel-cmdline \
		--pcrlock="$tmpdir/cmdline.pcrlock" \
		"$tmpdir/cmdline"
	pcrlock_file lock-kernel-initrd "$tmpdir/initrd.pcrlock" "$initrd" 2> /dev/null
	mkdir -p /var/lib/pcrlock.d/710-kernel-cmdline-initrd-entry.pcrlock.d
	jq --slurp '{"records": [.[].records[0]]}' \
	   "$tmpdir/cmdline.pcrlock" \
	   "$tmpdir/initrd.pcrlock" \
	   > "/var/lib/pcrlock.d/710-kernel-cmdline-initrd-entry.pcrlock.d/cmdline-initrd-$suffix.pcrlock"
	# 710-kernel-cmdline-boot-loader.pcrlock.d is not part of the
	# pcrlock standards.  It has the same measurement, in PCR 12.
	# See `pcrlock_loader_cmdline`
	mkdir -p /var/lib/pcrlock.d/710-kernel-cmdline-boot-loader.pcrlock.d
	jq -c '.records[].pcr = 12' "$tmpdir/cmdline.pcrlock" \
	   > "/var/lib/pcrlock.d/710-kernel-cmdline-boot-loader.pcrlock.d/cmdline-$suffix.pcrlock"
	rm "$tmpdir/cmdline" "$tmpdir/cmdline.pcrlock" "$tmpdir/initrd.pcrlock"
}

# The command line CMDLINE, as the boot loader (or systemd-stub, for an
# addon) measures it into PCR 12.  It is the same measurement that the
# kernel does into PCR 9.  But lock-kernel-cmdline ignores --pcr, so jq
# sets the PCR
pcrlock_loader_cmdline()
{
	local cmdline="$1" out="$2"

	echo -n "$cmdline" > "$tmpdir/cmdline"
	pcrlock lock-kernel-cmdline --pcrlock="$tmpdir/cmdline.pcrlock" "$tmpdir/cmdline"
	jq -c '.records[].pcr = 12' "$tmpdir/cmdline.pcrlock" > "$out"
	rm "$tmpdir/cmdline" "$tmpdir/cmdline.pcrlock"
}

# The command lines of the addons of a UKI entry, in PCR 12, as the
# variation SUFFIX of 710-kernel-cmdline-boot-loader.  The stub joins
# them with a space, and measures them as one.  Without addons it is the
# empty variation, because the stub measures nothing.  Its name sorts
# after the others, see systemd#36436
pcrlock_addons_cmdline()
{
	local suffix="$1"
	shift
	local dir=/var/lib/pcrlock.d/710-kernel-cmdline-boot-loader.pcrlock.d

	mkdir -p "$dir"
	if [ "$#" -eq 0 ]; then
		echo '{"records": []}' > "$dir/zz-empty.pcrlock"
		return 0
	fi
	pcrlock_loader_cmdline "$*" "$dir/addons-$suffix.pcrlock"
}

# The initrds of the addons FILE... of a UKI entry, in PCR 12.  The stub
# measures them after the command lines.  They are added to the
# variation SUFFIX of `pcrlock_addons_cmdline`
pcrlock_addons_initrd()
{
	local suffix="$1"
	shift
	local out=/var/lib/pcrlock.d/710-kernel-cmdline-boot-loader.pcrlock.d/addons-$suffix.pcrlock
	local file locks=() i=0
	for file in "$@"; do
		objcopy -O binary --only-section=.initrd "$file" "$tmpdir/addon-initrd" 2> /dev/null || continue
		[ -s "$tmpdir/addon-initrd" ] || continue
		i=$((i+1))
		pcrlock_file lock-raw "$tmpdir/addon-initrd-$i.pcrlock" "$tmpdir/addon-initrd" --pcr=12
		locks+=("$tmpdir/addon-initrd-$i.pcrlock")
	done
	rm -f "$tmpdir/addon-initrd"
	[ "$i" -gt 0 ] || return 0
	[ -e "$out" ] || echo '{"records": []}' > "$out"
	jq --slurp '{"records": ([.[].records[]])}' "$out" "${locks[@]}" > "$out.new"
	mv "$out.new" "$out"
	rm "${locks[@]}"
}

pcrlock_grub2_bls_kernel_initrd_cmdline_initrd()
{
	local linux="$1"
	local initrd="$2"
	local devicetree="$3"
	local cmdline="$4"
	local suffix="$5"

	# GRUB2-BLS >= 2.16 measures the initrd when the kernel loads it.
	# The kernel measures the cmdline before that
	local initrd_in_place=
	systemd-analyze compare-versions "$grub_version" "<" "2.16" || initrd_in_place=1

	local elements=("$linux")
	[ -n "$initrd_in_place" ] || elements+=("$initrd")
	[ -z "$devicetree" ] || elements+=("$devicetree")
	local locks=()
	local n=0
	for element in "${elements[@]}"; do
		n=$((n+1))
		pcrlock_file lock-raw "$tmpdir/element-$n.pcrlock" "$element" --pcr=9 2> /dev/null
		locks+=("$tmpdir/element-$n.pcrlock")
	done

	# systemd-boot and GRUB2-BLS >= 2.14 send the cmdline to the
	# kernel via UEFI with a null termination (a double \x00, as it
	# is UTF-16).  GRUB2-BLS <= 2.12 does not add it
	echo -n "$cmdline" > "$tmpdir/cmdline"
	n=$((n+1))
	if systemd-analyze compare-versions "$grub_version" "<" "2.13"; then
		iconv -t UTF-16LE -o "$tmpdir/cmdline.utf16" "$tmpdir/cmdline"
		pcrlock \
			lock-raw \
			--pcr=9 \
			--pcrlock="$tmpdir/element-$n.pcrlock" \
			"$tmpdir/cmdline.utf16"
		rm "$tmpdir/cmdline.utf16"
	else
		pcrlock \
			lock-kernel-cmdline \
			--pcrlock="$tmpdir/element-$n.pcrlock" \
			"$tmpdir/cmdline"
	fi
	locks+=("$tmpdir/element-$n.pcrlock")
	rm "$tmpdir/cmdline"

	if [ -n "$initrd_in_place" ]; then
		n=$((n+1))
		pcrlock_file lock-raw "$tmpdir/element-$n.pcrlock" "$initrd" --pcr=9 2> /dev/null
		locks+=("$tmpdir/element-$n.pcrlock")
	fi

	n=$((n+1))
	pcrlock_file lock-kernel-initrd "$tmpdir/element-$n.pcrlock" "$initrd" 2> /dev/null
	locks+=("$tmpdir/element-$n.pcrlock")

	mkdir -p /var/lib/pcrlock.d/710-grub2-bls-kernel-initrd-kernel-cmdline-initrd-entry.pcrlock.d
	jq --slurp '{"records": [.[].records[0]]}' \
	   "${locks[@]}" \
	   > "/var/lib/pcrlock.d/710-grub2-bls-kernel-initrd-kernel-cmdline-initrd-entry.pcrlock.d/kernel-initrd-cmdline-initrd-$suffix.pcrlock"
	rm "${locks[@]}"
}

pcrlock_grub2_bls_cmdline()
{
	local linux="$1"
	local cmdline="$2"
	local initrd="$3"
	local devicetree="$4"
	local suffix="$5"
	local lines=("$linux" "$cmdline" "$initrd")
	[ -z "$devicetree" ] || lines+=("$devicetree")

	local locks=()
	local n=0
	for line in "${lines[@]}"; do
		n=$((n+1))
		echo -n "$line" > "$tmpdir/line"
		pcrlock \
			lock-raw \
			--pcr=8 \
			--pcrlock "$tmpdir/line-$n.pcrlock" \
			"$tmpdir/line"
		locks+=("$tmpdir/line-$n.pcrlock")
		rm "$tmpdir/line"
	done
	mkdir -p /var/lib/pcrlock.d/650-grub2-bls-entry-cmdline.pcrlock.d
	jq --slurp '{"records": [.[].records[0]]}' \
	   "${locks[@]}" \
	   > "/var/lib/pcrlock.d/650-grub2-bls-entry-cmdline.pcrlock.d/cmdline-$suffix.pcrlock"
	rm "${locks[@]}"
}

pcrlock_grub2_bls_entry_files()
{
	local suffix="${1:+-$1}"
	local base="${2:-${boot_root}}"
	local locks=()
	local n=0
	for i in "$base"/loader/entries/*.conf; do
		n=$((n+1))
		[ "$base" != "${boot_root}" ] || track_esp_file "$i"
		pcrlock \
			lock-raw \
			--pcr=9 \
			--pcrlock="$tmpdir/entry-$n.pcrlock" \
			"$i"
		locks+=("$tmpdir/entry-$n.pcrlock")
	done
	mkdir -p /var/lib/pcrlock.d/643-grub2-bls-entry-files.pcrlock.d
	[ "${#locks[@]}" -eq 0 ] || {
		jq --slurp '{"records": [.[].records[0]]}' \
		   "${locks[@]}" \
		   > "/var/lib/pcrlock.d/643-grub2-bls-entry-files.pcrlock.d/generated$suffix.pcrlock"
		rm "${locks[@]}"
	}
}

# jq: the addons of an entry, in the order that systemd-stub loads
# them.  This is also the order of their measurements.  The global
# addons come first, then the ones of the entry.  Each group is sorted
# by file name
# shellcheck disable=SC2016  # jq
jq_addons_in_order='def addons_in_order:
	def name(f): f | split("/") | last;
	([.addons[]? | select(.globalAddon)] | sort_by(name(.globalAddon)))
	+ ([.addons[]? | select(.localAddon)] | sort_by(name(.localAddon)));'

pcrlock_sdboot()
{
	info "Generating TPM2 predictions with systemd-pcrlock (systemd-boot)"

	# 641-sdboot-loader-conf.pcrlock is not part of the pcrlock
	# standards
	if [ -e "${esp_root}/loader/loader.conf" ]; then
		shift_component 641-sdboot-loader-conf
		track_esp_file "${esp_root}/loader/loader.conf"
		pcrlock \
			lock-raw \
			--pcr=5 \
			--pcrlock=/var/lib/pcrlock.d/641-sdboot-loader-conf.pcrlock.d/generated.pcrlock \
			"${esp_root}/loader/loader.conf"
	fi

	# 650-kernel-efi-application.pcrlock is not part of the
	# pcrlock standards
	# TODO: move to kernel-TYPE-pcrlock.rpm
	# The image that the boot loader starts: the kernel, or the UKI
	# and then its addons.  The firmware measures them one after the
	# other.  For the UKI, `lock-uki` also gives the sections that
	# the stub measures into PCR 11, between the UKI and the addons.
	# There is one variation per entry, with all of its images
	shift_component 650-kernel-efi-application
	local n=0 kind images file missing locks i verb
	local -A kernels
	while IFS=$'\t' read -r kind images; do
		IFS=$'\t' read -r -a images <<< "$images"
		missing=
		for file in "${images[@]}"; do
			[ -f "${boot_root}$file" ] || missing="$file"
		done
		[ -z "$missing" ] || {
			info "Missing ${boot_root}$missing, ignoring entry for prediction"
			continue
		}
		[ -z "${kernels["${images[*]}"]}" ] || continue
		kernels["${images[*]}"]=1
		n=$((n+1))
		[ "$n" -le "${variation_limit[650-kernel-efi-application]}" ] || {
			info "Too many variations for 650-kernel-efi-application"
			continue
		}
		# A kernel is written as before.  So the variation of the
		# current boot is still the same file (`restore_shifts`)
		if [ "$kind" = "linux" ]; then
			track_esp_file "${boot_root}${images[0]}"
			pcrlock_file lock-pe \
				"/var/lib/pcrlock.d/650-kernel-efi-application.pcrlock.d/linux-$n.pcrlock" \
				"${boot_root}${images[0]}"
			continue
		fi
		# For the firmware, the addons are plain PE images.  The
		# stub measures none of their sections into PCR 11
		locks=()
		for i in "${!images[@]}"; do
			verb=lock-pe
			[ "$i" -gt 0 ] || verb=lock-uki
			track_esp_file "${boot_root}${images[$i]}"
			pcrlock_file "$verb" "$tmpdir/image-$i.pcrlock" "${boot_root}${images[$i]}"
			locks+=("$tmpdir/image-$i.pcrlock")
		done
		mkdir -p /var/lib/pcrlock.d/650-kernel-efi-application.pcrlock.d
		jq --slurp '{"records": [.[].records[]]}' "${locks[@]}" \
		   > "/var/lib/pcrlock.d/650-kernel-efi-application.pcrlock.d/uki-$n.pcrlock"
		rm "${locks[@]}"
	done < <(jq --raw-output "$jq_addons_in_order"'.[] | select(.uki or .linux) | if .uki then ["uki", .uki] + [addons_in_order[] | .globalAddon // .localAddon] else ["linux", .linux] end | join("\t")' "$entryfile")

	# Join the cmdline and the initrd in a single component
	shift_component 710-kernel-cmdline-initrd-entry
	shift_component 710-kernel-cmdline-boot-loader
	n=0
	while read -r cmdline; do
		read -r initrd
		read -r conf
		[ -f "${boot_root}$initrd" ] || {
			info "Missing ${boot_root}$initrd, ignoring entry for prediction"
			continue
		}
		n=$((n+1))
		# `get_final_pcrs` drops a PCR with more than 8 predicted
		# values (PolicyOR).  The values of a PCR are the product
		# of the variations of every component that measures it,
		# times two because of the separator.  Under systemd-boot
		# this is the only component that measures PCR 9.  So the
		# budget is 2*n <= 8.  Measured: 4 variations predict 8
		# values.  5 variations predict 10, and PCR 9 is dropped.
		# Then nothing constrains the kernel command line.  See
		# bsc#1274948
		[ "$n" -le "${variation_limit[710-kernel-cmdline-initrd-entry]}" ] || {
			info "Too many variations for 710-kernel-cmdline-initrd-entry"
			continue
		}
		# The command line is the "options" line of the entry
		track_esp_file "$conf"
		track_esp_file "${boot_root}$initrd"
		pcrlock_cmdline_initrd "initrd=$cmdline" "${boot_root}$initrd" "$n"
	done < <(jq --raw-output '.[] | select(.uki == null) | ([(.initrd[0] | sub("/"; "\\"; "g")), .options] | join(" ")), .initrd[0], .path' "$entryfile")

	# A UKI has no "options".  Instead, the stub measures the
	# command line of each addon into PCR 12.  Without addons it
	# measures nothing.  PCR 9 cannot be predicted for a UKI (see
	# `generate_tpm2_predictions_pcrlock`).  The initrds of the
	# addons go after their command lines
	local addons=() files=()
	while IFS=$'\t' read -r -a addons && IFS=$'\t' read -r -a files; do
		# Like the UKIs above, the addons must be in the ESP.  They
		# are tracked, because their content goes in the policy
		missing=
		for file in "${files[@]}"; do
			[ -f "${boot_root}$file" ] || missing="$file"
		done
		[ -z "$missing" ] || {
			info "Missing ${boot_root}$missing, ignoring entry for prediction"
			continue
		}
		for file in "${files[@]}"; do
			track_esp_file "${boot_root}$file"
		done
		n=$((n+1))
		# Like PCR 9 above, but for PCR 12
		[ "$n" -le "${variation_limit[710-kernel-cmdline-boot-loader]}" ] || {
			info "Too many variations for 710-kernel-cmdline-boot-loader"
			continue
		}
		pcrlock_addons_cmdline "$n" "${addons[@]}"
		pcrlock_addons_initrd "$n" "${files[@]/#/$boot_root}"
	done < <(jq --raw-output "$jq_addons_in_order"'.[] | select(.uki) | ([addons_in_order[] | .options // empty] | join("\t")),
						([addons_in_order[] | .globalAddon // .localAddon] | join("\t"))' "$entryfile")

	# Generate a variation of the 710-kernel-cmdline-initrd-entry
	# component with the current cmdline and the current initrd,
	# even if it is never used again.  This is needed because
	# disk-encryption-tool generates a new initrd during the first
	# boot.  That makes the event log impossible to align for
	# systemd-pcrlock
	#
	# These variations land in the same component as the loop
	# above, so "n" is not reset.  The budget is shared, and the
	# component stays inside the PolicyOR limit.  This only runs
	# from the installer (SDB_ADD_INITIAL_COMPONENT=1).  There is a
	# single snapshot there, and the loop above used almost nothing
	if [ "$SDB_ADD_INITIAL_COMPONENT" = "1" ]; then
		while read -r cmdline; do
			read -r initrd
			n=$((n+1))
			[ "$n" -le "${variation_limit[710-kernel-cmdline-initrd-entry]}" ] || {
				info "Too many variations for 710-kernel-cmdline-initrd-entry (initial)"
				continue
			}
			pcrlock_cmdline_initrd "initrd=$cmdline" "${tmpdir}$initrd" "0-$n"
		done < <(jq --raw-output '.[] | select(.uki == null) | ([(.initrd[0] | sub("/"; "\\"; "g")), .options] | join(" ")), .initrd[0]' "$initialentryfile")
	fi
}

pcrlock_grub2_bls()
{
	info "Generating TPM2 predictions with systemd-pcrlock (grub2-bls)"

	# Read the version once.  `bootloader_version` greps the whole
	# binary, and the helpers below compare the version for every
	# entry
	local grub_version n
	grub_version="$(bootloader_version)" || grub_version=
	[ -n "$grub_version" ] || warn "Cannot read the version of grub2-bls, the prediction is done as for an old version"

	# 641-grub2-bls-grubenv.pcrlock is not part of the pcrlock
	# standards
	if [ -e "${esp_root}${esp_dst}/grubenv" ]; then
		shift_component 641-grub2-bls-grubenv
		track_esp_file "${esp_root}${esp_dst}/grubenv"
		pcrlock \
			lock-raw \
			--pcr=9 \
			--pcrlock=/var/lib/pcrlock.d/641-grub2-bls-grubenv.pcrlock.d/generated.pcrlock \
			"${esp_root}${esp_dst}/grubenv"
	fi

	# 643-grub2-bls-entry-files.pcrlock is not part of the pcrlock
	# standards
	shift_component 643-grub2-bls-entry-files
	pcrlock_grub2_bls_entry_files
	if [ "$SDB_ADD_INITIAL_COMPONENT" = "1" ]; then
		pcrlock_grub2_bls_entry_files "0" "$tmpdir"
	fi

	local grub2_bls_drive
	if systemd-analyze compare-versions "$grub_version" "<" "2.13"; then
		local partno
		read -r _ partno dseq < <(esp_root_drive_partno_dseq)
		# We assume that the disk sequence (it starts at 1)
		# matches the disk number that GRUB2 sees at boot (it
		# starts at 0).  `esp_root_drive_partno_dseq` already
		# returns the number with the right start.
		#
		# Since GRUB2 2.14 the measured path has no drive, so the
		# drive is only set for older versions
		grub2_bls_drive="(hd$dseq,gpt$partno)"
	fi

	# Join linux, initrd and cmdline in a single pcrlock file
	shift_component 650-grub2-bls-entry-cmdline
	n=0
	while read -r options; do
		read -r linux
		read -r initrd
		read -r devicetree
		[ -f "${esp_root}$linux" ] || {
			info "Missing ${esp_root}$linux, ignoring entry for prediction"
			continue
		}
		[ -f "${esp_root}$initrd" ] || {
			info "Missing ${esp_root}$initrd, ignoring entry for prediction"
			continue
		}
		if [ -n "$devicetree" ] && [ ! -f "${esp_root}$devicetree" ]; then
			info "Missing ${esp_root}$devicetree, ignoring entry for prediction"
			continue
		fi
		n=$((n+1))
		[ "$n" -le "${variation_limit[650-grub2-bls-entry-cmdline]}" ] || {
			info "Too many variations for 650-grub2-bls-entry-cmdline"
			continue
		}
		pcrlock_grub2_bls_cmdline "linux ${grub2_bls_drive}$linux $options" \
					  "${grub2_bls_drive}$linux $options" \
					  "initrd ${grub2_bls_drive}$initrd" \
					  "${devicetree:+devicetree ${grub2_bls_drive}$devicetree}" \
					  "$n"
	done < <(jq --raw-output '.[] | .options, .linux, .initrd[0], (.devicetree // "")' "$entryfile")

	# Add a variation to the 650-grub2-bls-entry-cmdline component,
	# with the current cmdline and the current initrd.  This
	# variation is never used again.  It is needed because
	# disk-encryption-tool makes a new initrd during the first boot.
	# Without it, systemd-pcrlock cannot align the event log
	#
	# These variations go in the same component as the loop above,
	# so "n" is not reset.  Both loops share one budget, and the
	# component stays inside the PolicyOR limit
	if [ "$SDB_ADD_INITIAL_COMPONENT" = "1" ]; then
		while read -r options; do
			read -r linux
			read -r initrd
			read -r devicetree
			n=$((n+1))
			[ "$n" -le "${variation_limit[650-grub2-bls-entry-cmdline]}" ] || {
				info "Too many variations for 650-grub2-bls-entry-cmdline (initial)"
				continue
			}
			pcrlock_grub2_bls_cmdline "linux ${grub2_bls_drive}$linux $options" \
						  "${grub2_bls_drive}$linux $options" \
						  "initrd ${grub2_bls_drive}$initrd" \
						  "${devicetree:+devicetree ${grub2_bls_drive}$devicetree}" \
						  "0-$n"
		done < <(jq --raw-output '.[] | .options, .linux, .initrd[0], (.devicetree // "")' "$initialentryfile")
	fi

	# If shim is installed, grub2-bls calls shim to extend PCR 4
	if is_shim_installed || is_secure_boot; then
		# 650-kernel-efi-application.pcrlock is not part of
		# the pcrlock standards
		# TODO: move to kernel-TYPE-pcrlock.rpm
		shift_component 650-kernel-efi-application
		local n=0
		local -A kernels
		while read -r linux; do
			[ -f "${esp_root}$linux" ] || {
				info "Missing ${esp_root}$linux, ignoring entry for prediction"
				continue
			}
			[ -z "${kernels["$linux"]}" ] || continue
			kernels["$linux"]=1
			n=$((n+1))
			[ "$n" -le "${variation_limit[650-kernel-efi-application]}" ] || {
				info "Too many variations for 650-kernel-efi-application"
				continue
			}
			track_esp_file "${esp_root}/$linux"
			pcrlock_file lock-pe \
				"/var/lib/pcrlock.d/650-kernel-efi-application.pcrlock.d/linux-$n.pcrlock" \
				"${esp_root}/$linux"
		done < <(jq --raw-output 'map(.linux) | .[]' "$entryfile")
	fi

	# With GRUB2-BLS, MicroOS can easily go over the PolicyOR limit
	# of 8 values for PCR 9.  Each update changes these components:
	#  - 641-grub2-bls-grubenv: `grubenv` changes after the
	#    `set-default` of the new boot entry
	#  - 643-grub2-bls-entry-files: a new boot entry is added
	#  - 710-kernel-cmdline-initrd-entry: each snapshot needs its own
	#    cmdline (rootflags), so there is one variation per snapshot
	#  - 710-grub2-bls-kernel-initrd-entry: a new kernel or initrd
	#    adds a variation with different hashes
	#
	# When no kernel or initrd is updated, PCR 9 can have these
	# values.  641 has 2: the shift and the new `grubenv`.  643 has
	# 2: the shift and the new entry.  710-kernel has n, one per
	# snapshot.  710-grub2 has 2, but only for a new kernel or
	# initrd.  The product is [2x]2xn[x2]
	#
	# Solutions:
	#  - GRUB2-BLS uses BLI and drops `grubenv`  [done, GRUB2 2.14]
	#  - MicroOS uses only systemd-boot
	#  - systemd-pcrlock removes the PolicyOR limit
	#  - Merge both 710 components, to have fewer variations
	#    [done, see below]
	#  - Make n=2 (710-kernel-cmdline-initrd-entry)  [done, it is the
	#    cap of the merged component below]
	#
	# With the first and the last solutions the product is 2
	# (separator) x 1 (641, `grubenv` is not written again) x 2
	# (643) x 2 (the merged 710) = 8.  8 is the limit.  641 is only
	# 1 while the EFI variables can be used.  With GRUB2 2.12,
	# without efivars or with `--no-variables`, `grubenv` is written
	# again on every `set-default`, and PCR 9 is dropped.
	#
	# The merged component has this order:
	#  - GRUB2: full sha256 of the kernel
	#  - GRUB2: sha256 of the initrd
	#  - Kernel: sha256 of the cmdline
	#  - Kernel: sha256 of the initrd (again)
	#
	# UEFI or shim also measure the kernel into PCR 4, as pesign
	# does.  This is the 650-kernel-efi-application component

	# Remove old components before the merge
	rm -fr /var/lib/pcrlock.d/710-grub2-bls-kernel-initrd-entry.pcrlock.d
	rm -fr /var/lib/pcrlock.d/710-kernel-cmdline-initrd-entry.pcrlock.d

	# Join the kernel and initrd (measured by GRUB2) and the cmdline
	# and initrd (measured by the kernel) in a single component
	shift_component 710-grub2-bls-kernel-initrd-kernel-cmdline-initrd-entry
	n=0
	while read -r cmdline; do
		read -r linux
		read -r initrd
		read -r devicetree
		[ -f "${esp_root}$linux" ] || {
			info "Missing ${esp_root}$linux, ignoring entry for prediction"
			continue
		}
		[ -f "${esp_root}$initrd" ] || {
			info "Missing ${esp_root}$initrd, ignoring entry for prediction"
			continue
		}
		if [ -n "$devicetree" ] && [ ! -f "${esp_root}$devicetree" ]; then
			info "Missing ${esp_root}$devicetree, ignoring entry for prediction"
			continue
		fi
		n=$((n+1))
		# `get_final_pcrs` drops a PCR with more than 8
		# predicted values (PolicyOR).  The number of values of
		# a PCR is the product of the variations of each
		# component that measures it, times 2 for the separator.
		# For PCR 9 that is 2 * 641 * 643 * n.
		#
		# 641-grub2-bls-grubenv is 1.  Since GRUB2 2.14 the
		# default entry and the timeout are in EFI variables
		# (see `set_default_grub2_bls`).  So `grubenv` is never
		# written again, and its variation is the same as the
		# shifted one.
		#
		# 643-grub2-bls-entry-files is 2 when an entry was added
		# or removed since the last boot.  This is exactly when
		# the predictions are made again, so it must be counted.
		#
		# So 2 * 1 * 2 * n <= 8, and n <= 2.  This was measured
		# on grub2-bls with n=4: 8 values while 643 is stable,
		# and 16 when it shifts.  See bsc#1274948
		[ "$n" -le "${variation_limit[710-grub2-bls-kernel-initrd-kernel-cmdline-initrd-entry]}" ] || {
			info "Too many variations for 710-grub2-bls-kernel-initrd-kernel-cmdline-initrd-entry"
			continue
		}
		track_esp_file "${esp_root}$linux"
		track_esp_file "${esp_root}$initrd"
		[ -z "$devicetree" ] || track_esp_file "${esp_root}$devicetree"
		pcrlock_grub2_bls_kernel_initrd_cmdline_initrd \
			"${esp_root}$linux" "${esp_root}$initrd" \
			"${devicetree:+${esp_root}$devicetree}" \
			"BOOT_IMAGE=${grub2_bls_drive}$linux $cmdline" \
			"$n"
	done < <(jq --raw-output '.[] | .options, .linux, .initrd[0], (.devicetree // "")' "$entryfile")

	# Add a variation to
	# 710-grub2-bls-kernel-initrd-kernel-cmdline-initrd-entry, for
	# the same reason as above (the initrd of the first boot).
	#
	# These variations go in the same component as the loop above,
	# so "n" is not reset.  Both loops share one budget, and the
	# component stays inside the PolicyOR limit
	if [ "$SDB_ADD_INITIAL_COMPONENT" = "1" ]; then
		while read -r cmdline; do
			read -r linux
			read -r initrd
			read -r devicetree
			n=$((n+1))
			[ "$n" -le "${variation_limit[710-grub2-bls-kernel-initrd-kernel-cmdline-initrd-entry]}" ] || {
				info "Too many variations for 710-grub2-bls-kernel-initrd-kernel-cmdline-initrd-entry (initial)"
				continue
			}
			pcrlock_grub2_bls_kernel_initrd_cmdline_initrd \
				"${tmpdir}$linux" "${tmpdir}$initrd" \
				"${devicetree:+${tmpdir}$devicetree}" \
				"BOOT_IMAGE=${grub2_bls_drive}$linux $cmdline" \
				"0-$n"
		done < <(jq --raw-output '.[] | .options, .linux, .initrd[0], (.devicetree // "")' "$initialentryfile")
	fi
}

clean_pcrlock_d()
{
	[ -d /var/lib/pcrlock.d ] || return 0

	# Remove the shifted measurements made before the last reboot.
	# They link the current components with the event log, so
	# pcrlock can align them.  For example, when a file is replaced
	# (loader.conf), its new measurement is not in the event log.
	# The event log has the old hash, so the alignment fails.
	#
	# The masks (see `mask_unmatched_components`) also describe the
	# current event log, so they expire in the same way.  A
	# measurement that is missing today can appear in a later boot.
	# For example, the initrd can gain `systemd-pcrextend`.  Then
	# the mask would hide the component of that measurement, and the
	# new records would drop the PCR from the policy.  A missing
	# component is reported and can be masked.  A record that no
	# component claims cannot be fixed.  So the masks are dropped
	# after every reboot, and checked again.  The name cannot
	# identify a mask, because a mask must have the name of the
	# component that it hides.  But the masks are the only empty
	# files in the directory
	local btime
	read -r _ btime < <(grep btime /proc/stat)
	local minutes=$((1 + ($(date +%s) - btime) / 60))
	dbg "Cleaning shifted and masked measurements older than $minutes minutes"
	find /var/lib/pcrlock.d -type f \
	     \( -name 'shift-*.pcrlock' -o \( -name '*.pcrlock' -empty \) \) \
	     -cmin +"$minutes" -delete

	find /var/lib/pcrlock.d -mindepth 1 -type d -empty -delete
}

get_predicted_hashes()
{
	# The directory is missing when nothing made a component yet.
	# This is a valid state, so `find` must not print an error
	[ -d /var/lib/pcrlock.d ] || return 0

	find /var/lib/pcrlock.d/ -name "*.pcrlock" -type f -exec jq -r '.records[].digests[] | select(.hashAlg == "sha256") | .digest' {} + | sort -u
}

component_pcrs()
{
	# The PCRs that a component measures, read from its `.pcrlock`
	# files.  A component is a single file or a directory of
	# variations.  Both forms can be in any of the `systemd-pcrlock`
	# directories, so all of them are read
	local component="$1"

	local d f
	local -a files=()
	for d in /etc/pcrlock.d /run/pcrlock.d /var/lib/pcrlock.d \
		 /usr/local/lib/pcrlock.d /usr/lib/pcrlock.d; do
		for f in "$d/$component.pcrlock" "$d/$component.pcrlock.d"/*.pcrlock; do
			# A mask is an empty file, and `jq` fails on it
			[ -s "$f" ] || continue
			files+=("$f")
		done
	done

	[ "${#files[@]}" -gt 0 ] || return 0

	jq -r '.records[] | .pcr // empty' "${files[@]}" 2>/dev/null | sort -nu
}

mask_unmatched_components()
{
	# `systemd-pcrlock` removes a PCR from the protection mask when
	# a component that touches it is not found in the event log.
	# Some components shipped in /usr/lib/pcrlock.d describe
	# measurements that this system never does.  For example,
	# `systemd-pcrextend` measures `750-enter-initrd` and
	# `750-os-separator`, and it is not always in the initrd.
	# `750-os-separator` touches PCRs 0-7, 9 and 12-14.  So one
	# missing component can leave the policy with no PCR at all.
	#
	# A component is masked with an empty file in a directory with
	# more priority.  The mask must have the name of the component.
	# This is because `systemd-pcrlock` collects the components with
	# `conf_files_list_strv`, and this function resolves the
	# priority and the masks by file name.  A symlink to /dev/null
	# is also a mask, but the SELinux policy does not allow
	# `lnk_file` in the pcrlock directory.  Only the components
	# shipped by the system are masked.  A component made here is
	# already in the directory with more priority, so no file can
	# hide it.
	#
	# The mask describes the current event log.  So
	# `clean_pcrlock_d` drops it after a reboot, like the shifted
	# measurements.
	#
	# Returns 0 if something was masked.  Then the caller knows that
	# the prediction is stale
	local pcrs="$1"

	local i
	local -a list
	local -A requested
	IFS=',' read -r -a list <<<"$pcrs"
	for i in "${list[@]}"; do
		requested[$i]=1
	done

	local component masked=1
	while read -r component; do
		[ -e "/usr/lib/pcrlock.d/$component.pcrlock" ] || \
		    [ -d "/usr/lib/pcrlock.d/$component.pcrlock.d" ] || {
			# A component made here has no copy with lower
			# priority to hide, so it cannot be masked.
			# This is only a problem when the component
			# touches a sealed PCR.  For example, `600-gpt`
			# cannot align in the boot that rewrites the
			# partition table (a disk image grown to the
			# size of the disk, or `systemd-repart`).  The
			# firmware measured the old table.  PCR 5 is not
			# in any of the default lists
			local affected=
			for i in $(component_pcrs "$component"); do
				[ -n "${requested[$i]+_}" ] || continue
				affected+="${affected:+,}$i"
			done
			if [ -z "$affected" ]; then
				info "Component $component cannot be found in the event log, no sealed PCR is affected"
			else
				warn "Component $component cannot be found in the event log, PCR $affected cannot be predicted"
			fi
			continue
		}
		[ ! -e "/var/lib/pcrlock.d/$component.pcrlock" ] || continue
		info "Masking component $component (not found in the event log)"
		: > "/var/lib/pcrlock.d/$component.pcrlock"
		masked=0
	done < <(sed -n "s/^Couldn't find component '\(.*\)' in event log\.\$/\1/p" "$tmpfile")

	return "$masked"
}

predict_pcrs()
{
	local pcrs="$1"

	# `mask_unmatched_components` needs the components that cannot
	# be aligned.  Since systemd 262 they are reported at `info`
	# level (`notice` before).  So `notice` would hide them
	SYSTEMD_LOG_LEVEL=info pcrlock --pcr="$pcrs" --json=short predict 2>"$tmpfile"
}

remove_pcr()
{
	local pcrs=",$1,"
	pcrs="${pcrs//,$2,/,}"
	pcrs="${pcrs#,}"
	echo "${pcrs%,}"
}

policy_missing_pcrs()
{
	# The requested PCRs that the current policy does not bind.  The
	# policy stores its list of PCRs, so nothing has to be tracked
	# here
	local pcrs="$1"

	[ -e /var/lib/systemd/pcrlock.json ] || return 0
	jq -r --arg pcrs "$pcrs" '($pcrs | split(",") | map(select(. != "") | tonumber)) - [.pcrValues[].pcr] | join(",")' \
		< /var/lib/systemd/pcrlock.json
}

# Bound PCRs that are no longer requested
policy_extra_pcrs()
{
	local pcrs="$1"

	[ -e /var/lib/systemd/pcrlock.json ] || return 0
	jq -r --arg pcrs "$pcrs" '[.pcrValues[].pcr] - ($pcrs | split(",") | map(select(. != "") | tonumber)) | join(",")' \
		< /var/lib/systemd/pcrlock.json
}

policy_stale_pcrs()
{
	# The bound PCRs whose current value is not one of the values
	# that the policy accepts.  The TPM2 checks exactly this when it
	# unseals the recovery PIN to authorize the NVIndex again.  Here
	# the check costs two reads and needs no secret
	[ -e /var/lib/systemd/pcrlock.json ] || return 0

	local bank
	bank="$(jq -r '.pcrBank // "sha256"' < /var/lib/systemd/pcrlock.json)"

	local i current stale=
	while read -r i; do
		# A PCR that the kernel does not export cannot be
		# compared.  Assuming the worst would report a problem
		# that may not exist
		[ -r "/sys/class/tpm/tpm0/pcr-$bank/$i" ] || continue
		# sysfs writes the values in upper case, the policy in
		# lower case
		current="$(tr '[:upper:]' '[:lower:]' < "/sys/class/tpm/tpm0/pcr-$bank/$i")"
		jq -e --arg c "$current" --argjson p "$i" \
		   '.pcrValues[] | select(.pcr == $p) | .values | index($c)' \
		   < /var/lib/systemd/pcrlock.json > /dev/null || \
			stale+="${stale:+,}$i"
	done < <(jq -r '.pcrValues[].pcr' < /var/lib/systemd/pcrlock.json)

	echo "$stale"
}

# What a PCR measures, and what changes it in a normal way.  The second
# half of each line is what matters.  A PCR number alone does not tell
# the user if they made the change
pcr_meaning()
{
	case "${1:?}" in
		0)  echo "firmware code. A firmware update moves it" ;;
		1)  echo "firmware settings. A BIOS setting or boot order change moves it" ;;
		2)  echo "option ROM code. Adding or removing a plug-in card moves it" ;;
		3)  echo "option ROM settings. Adding or removing a plug-in card moves it" ;;
		4)  echo "the boot loader binaries. A shim, systemd-boot or GRUB2 update moves it, and so does booting another entry" ;;
		5)  echo "the partition table. Adding, removing or resizing a partition moves it" ;;
		7)  echo "secure boot state and certificates. Toggling secure boot, or a keys, db or dbx update, moves it" ;;
		8)  echo "the GRUB2 commands. Editing the command line or the GRUB2 configuration moves it" ;;
		9)  echo "the kernel and initrd. A kernel or initrd update moves it" ;;
		11) echo "the UKI sections. A kernel update moves it" ;;
		12) echo "the kernel command line and credentials. Editing either moves it" ;;
		14) echo "the shim MOK certificates. Using mokutil moves it" ;;
		*)  echo "something this tool cannot describe" ;;
	esac
}

# The two places where a recovery PIN can be read, as
# "keyring:environment".  Each flag is "1" or empty, so a caller can
# report them one by one.  When both are empty, the only copy left is
# the one sealed in the TPM2.  It can only be unsealed while the PCRs
# still match the policy
recovery_pin_sources()
{
	local keyring="" environment=""

	! recovery_pin_keyid > /dev/null 2>&1 || keyring=1
	[ -z "${env_recovery_pin:+set}${env_pin:+set}" ] || environment=1

	echo "$keyring:$environment"
}

# The enrolled TPM2 method, for the commands that the warnings below ask
# the user to run.  `unenroll` cannot tell "tpm2" from "tpm2+pin",
# because both wipe the same slot.  But `enroll` can: only "tpm2+pin"
# passes `--tpm2-with-pin=1`.  Advising "tpm2" on a machine that asks
# for a PIN at boot would enroll it without a PIN, and nobody would
# notice.  Only the LUKS2 header knows the method.  When it cannot be
# read, the answer is "tpm2".  This is the safe answer, and it is also
# the method that the machine has
enrolled_tpm2_method()
{
	local dev

	if detect_tracked_devices; then
		for dev in "${tracked_devices[@]}"; do
			luks_header "$dev" 2> /dev/null | jq -e '
				[ (.tokens // {})[]
				  | select(.type == "systemd-tpm2")
				  | ."tpm2-pin" // false ] | any' \
				> /dev/null 2>&1 || continue
			echo "tpm2+pin"
			return 0
		done
	fi

	echo "tpm2"
}

# A PIN that cannot be read here is the normal state, not a problem.
# `systemd-pcrlock` always seals one in the policy metadata.  The
# keyring copy lives $keyctl_timeout seconds and never survives a
# reboot.  After that, every update unseals the sealed PIN with no help,
# because the PCRs still match the policy that sealed it.
#
# The dead end is when that unseal fails.  A bound PCR that moved out of
# the values that the policy accepts locks the NVIndex.  Without a PIN
# that can be read, every later `update-predictions` fails the same way
# (github issue 250).  So this warns only when both conditions hold.
# The check is here, and not only in `status`, because this runs on
# every kernel and boot loader update.  Nobody runs `status` before they
# hit the problem.  Right after a policy is written, the PCRs match by
# construction.  So in practice this matters on the "Policy is up to
# date" return.  That is the one path where nothing authorizes the
# NVIndex, so a stale PCR would stay unreported until the next change
warn_no_recovery_pin()
{
	[ "$(recovery_pin_sources)" = ":" ] || return 0

	local stale
	stale="$(policy_stale_pcrs)"
	[ -n "$stale" ] || return 0

	warn "PCR $stale no longer match the policy, and no recovery PIN is reachable, so every 'update-predictions' from now on fails the same way"
	explain_pcrlock_recovery "$stale"
}

# Explain what the PCRs that moved measure, and give the two ways out.
# Both ways trust the current boot path, so the user must rule out
# tampering first.  The list can be empty when sysfs does not export the
# PCRs
explain_pcrlock_recovery()
{
	local i
	for i in ${1//,/ }; do
		warn "PCR $i measures $(pcr_meaning "$i")"
	done

	local m
	m="$(enrolled_tpm2_method)"
	warn "If you made no such change, the boot path was altered. Both fixes below trust the current state, so explain it first"
	warn "With the recovery PIN: re-run with --ask-recovery-pin (or RECOVERY_PIN=...)"
	warn "Without it: check that a password opens the devices, then 'sdbootutil unenroll --method=$m' and 'sdbootutil enroll --method=$m --ask-recovery-pin'"
}

# `systemd-pcrlock make-policy` must authorize the NVIndex against the
# policy that is already stored in it.  With a recovery PIN this is a
# PolicySigned, and no PCR takes part.  Without one, the PIN is first
# unsealed from the TPM2.  That unseal checks the *previous* prediction
# against the *current* PCR values.  So a PCR that moved out of what the
# last policy accepted blocks the update.  The same failure comes back
# at every boot.  Retrying, or making the components again, does not
# change it.  This is github issue 250.  There, enrolling again was the
# only way out, and nobody could say why
#
# The strings come from `tpm2_policy_super_pcr()`.  "None of the
# alternative values" is for a PCR with several values.  The retry
# message is for a PCR with one value that keeps not matching.  systemd
# 258 (3ab04fbc4c) added both.  Older versions only print the
# `Esys_PolicyOR` failure and "Failed to submit super PCR policy"
explain_pcrlock_policy_error()
{
	local errorfile="$1"
	# The name of the variable with the recovery PIN, see "Secrets and
	# --start-trace-code"
	local pin_name="$2"

	# A recovery PIN was used, so the PCRs were not part of the
	# authorization.  This is a different problem.  The PIN must
	# satisfy the PolicySigned of the NVIndex.  When the TPM2
	# refuses the write, the PIN is wrong.  Talking about PCRs here
	# would send the reader the wrong way
	if [ -n "${!pin_name:+set}" ]; then
		grep -q "Failed to write to NV index" "$errorfile" || return 0

		warn "The TPM2 rejected the recovery PIN, so the NVIndex keeps the policy it had"

		# The recovery key and the recovery PIN are meant to be
		# the same secret.  Before, a key enrolled while the PIN
		# was out of reach was published as the PIN.  A "PIN"
		# that opens the devices comes from that mistake, and it
		# cannot become the PIN.  `systemd-pcrlock` authorizes
		# the NVIndex only with the PIN that sealed it
		local dev
		for dev in "${tracked_devices[@]}"; do
			valid_password "$dev" "$pin_name" || continue
			warn "That value opens $dev, so it is the recovery key and not the recovery PIN of the NVIndex"
			break
		done

		local m
		m="$(enrolled_tpm2_method)"
		warn "Use the recovery PIN that sealed the NVIndex, or start again with one you keep: 'sdbootutil unenroll --method=$m' then 'sdbootutil enroll --method=$m --ask-recovery-pin'"
		return 0
	fi

	local stale
	stale="$(policy_stale_pcrs)"

	# The place where the authorization fails decides what is
	# printed.  `tpm2_policy_super_pcr()` names the PCR that it
	# could not satisfy.  But the same stale PCR can instead break
	# the later `Esys_PolicyAuthorizeNV`, and that error says
	# nothing about PCRs.  Both are the same condition.  So the
	# second form is only used when a PCR really moved.  Any other
	# TPM2 error in PolicyAuthorizeNV must not get this explanation
	if ! grep -qE "None of the alternative values|PCR values kept changing|Failed to submit super PCR policy|Failed to unseal PIN" "$errorfile"; then
		[ -n "$stale" ] || return 0
		grep -qE "Failed to submit AuthorizeNV policy" "$errorfile" || return 0
	fi

	warn "The TPM2 policy cannot be re-authorized${stale:+: PCR $stale moved}. No recovery PIN was available, so every new run fails the same way"
	explain_pcrlock_recovery "$stale"
}

shim_changed()
{
	# The shim in the ESP is not the one that made the current event
	# log.  `restore_shifts` keeps the variation of the current boot
	# only when it differs from the one made for the installed
	# binary
	local dir=/var/lib/pcrlock.d/630-shim-efi-application.pcrlock.d
	# With nullglob, the list is empty when there is no shifted
	# variation
	local shifted=("$dir"/shift-*.pcrlock)

	[ -e "$dir/generated.pcrlock" ] && [ "${#shifted[@]}" -gt 0 ]
}

get_final_pcrs()
{
	local pcrs="$1"

	# For systemd-pcrlock, an empty "--pcr=" is not "no PCR".  It
	# means its default list
	[ -n "$pcrs" ] || {
		warn "No PCR is left for the policy"
		return 1
	}

	# Make a JSON prediction, to get the final PCRs of the policy.
	# The PCRs with more than 8 values are filtered out, because of
	# the PolicyOR limit
	#
	# The status is read in the same command.  With `set -e`, a
	# failing command substitution ends the shell before the error
	# in $tmpfile is printed.  When a component was masked, the
	# prediction runs again, because the first one had the component
	# in place
	local output
	if ! output="$(predict_pcrs "$pcrs")" || \
	   { mask_unmatched_components "$pcrs" && ! output="$(predict_pcrs "$pcrs")"; }; then
		warn "Error creating the systemd-pcrlock prediction!\n$(cat "$tmpfile")"
		return 1
	fi

	# An empty prediction means that no PCR is left after the event
	# log alignment.  A policy can still be made from it.  But that
	# policy binds the NVIndex to no PCR, and the protection that
	# the user asked for is gone without a word
	[ "$output" != "{}" ] || {
		warn "No PCR from $pcrs can be predicted, the event log cannot be aligned!\n$(cat "$tmpfile")"
		return 1
	}

	# PCRs that participate in the policy
	local pcrs_policy
	pcrs_policy="$(jq -r '[.sha256[] | select(.values | length <= 8) | .pcr] | join(",")' <<<"$output")"

	# PCRs dropped because they have more than 8 values
	local pcrs_policyor
	pcrs_policyor="$(jq -r '[.sha256[] | select(.values | length > 8) | .pcr] | join(",")' <<<"$output")"

	# A PCR dropped by the PolicyOR limit is also missing from the
	# policy, so it is not reported twice.  The list keeps the order
	# that the user requested
	local i pcrs_policy_missing=
	for i in ${pcrs//,/ }; do
		[[ ",$pcrs_policy,$pcrs_policyor," == *",$i,"* ]] || pcrs_policy_missing+="${pcrs_policy_missing:+,}$i"
	done

	# `systemd-pcrlock` can say that a PCR matches the event log,
	# and still predict values that do not contain the current one.
	# This happens for example when a component is replayed in the
	# wrong order.  The policy is valid, but the device will not
	# unseal after a reboot that changes nothing.  So it is reported
	local pcr_current
	for i in ${pcrs_policy//,/ }; do
		[ -e "/sys/class/tpm/tpm0/pcr-sha256/$i" ] || continue
		read -r pcr_current < "/sys/class/tpm/tpm0/pcr-sha256/$i"
		jq -e --argjson pcr "$i" --arg value "${pcr_current,,}" \
			'[.sha256[] | select(.pcr == $pcr) | .values[]] | index($value)' \
			<<<"$output" > /dev/null || \
			warn "The prediction for PCR $i does not contain the current value"
	done

	# Dropping a PCR removes protection that the user asked for, so
	# it is a warning and not an `info`.  `info` prints nothing
	# without `--verbose`, and the enroll and installer paths are
	# not verbose
	[ -z "$pcrs_policy_missing" ] || warn "PCRs $pcrs_policy_missing dropped from the policy (component mapping)"
	[ -z "$pcrs_policyor" ] || warn "PCRs $pcrs_policyor dropped from the policy (PolicyOR)"
	[ "$pcrs" = "$pcrs_policy" ] || info "Final PCRs list ($pcrs -> $pcrs_policy)"

	# With `--strict` the requested list is taken literally.  If a
	# PCR cannot be predicted, nothing is applied, and the warnings
	# above give the reasons.  `systemd-pcrlock --strict=` does the
	# same for the PCRs that it drops itself.  Here it is extended
	# to the PolicyOR limit, which is our own check
	#
	# Without `--strict`, a smaller policy is applied.  The list
	# usually comes from the configuration file or from the
	# defaults.  There it can name a PCR that this machine cannot
	# predict, and that is fine.  Refusing to update would leave the
	# system with a stale policy after every kernel update
	#
	# `err` exits the command substitution of the caller.  So the
	# caller sees a failure, and stops before it makes any policy
	[ -z "$arg_strict" ] || [ -z "$pcrs_policy_missing$pcrs_policyor" ] || \
		err "Not all the requested PCRs can be predicted ($pcrs -> ${pcrs_policy:-none}). No policy is applied, run without --strict to accept the subset"

	[ -n "$pcrs_policy" ] || {
		warn "No PCR from $pcrs can be part of the policy"
		return 1
	}
	echo "$pcrs_policy"
}

# Put the recovery PIN for `make-policy` in the variable named $1.  It
# comes from the first source that has one.  Put the matching
# --recovery-pin option in the array named $2.  This is not traced, see
# "Secrets and --start-trace-code"
# shellcheck disable=SC2034  # the namerefs are written for the caller
recovery_pin_for_policy()
{
	local -; set +x
	local rpp_name="$1"
	local -n rpp_pin="$1" rpp_extra="$2"
	local keyid keyid_int
	keyid="$(keyctl id %user:sdbootutil 2> /dev/null)" || true
	keyid_int="$(recovery_pin_keyid)" || true
	# For "tpm2+pin", PIN and %user:sdbootutil hold the TPM2 PIN
	# that is typed at every boot.  That PIN must not also be the
	# recovery PIN.  The recovery PIN authorizes the NVIndex again,
	# so seeing the boot PIN once would be enough to rewrite the
	# policy.  With --ask-pin both PINs are already asked
	# separately.  RECOVERY_PIN and %user:sdbootutil-recovery-pin
	# always name the recovery PIN, so they are still read.  With no
	# source left, systemd-pcrlock makes a PIN, and it is printed
	# later
	local pin_env="$env_pin"
	if [ "$arg_method" = "tpm2+pin" ]; then
		pin_env=
		keyid=
	fi
	# RECOVERY_PIN has only one meaning, so it wins over PIN, which
	# has two.  For "tpm2+pin" it is the only environment variable
	# that is read
	[ -z "$env_recovery_pin" ] || pin_env="$env_recovery_pin"
	if [ -n "$arg_ask_pin$arg_ask_recovery_pin" ]; then
		# When enrolling, ask twice
		if [ -n "$arg_method" ]; then
			info "The recovery PIN is used when the TPM2 policy needs to be updated"
			ask_new_password "recovery PIN" "$rpp_name"
		else
			ask_password "Recovery PIN" "$rpp_name"
		fi
		rpp_extra=("--recovery-pin=yes")
	elif [ -n "$pin_env" ]; then
		rpp_pin="$pin_env"
		rpp_extra=("--recovery-pin=yes")
	elif [ -n "$keyid_int" ]; then
		rpp_pin="$(keyctl pipe "$keyid_int")"
		rpp_extra=("--recovery-pin=yes")
	elif [ -n "$keyid" ]; then
		deprecated_keyring_secret "recovery PIN" "sdbootutil-recovery-pin"
		rpp_pin="$(keyctl pipe "$keyid")"
		rpp_extra=("--recovery-pin=yes")
	else
		# No PIN was given, so systemd-pcrlock makes one
		rpp_extra=("--recovery-pin=show")
	fi
}

# Run `make-policy` with the recovery PIN in the variable named $1.
# When there was no PIN, systemd-pcrlock makes one and its output shows
# it.  So the output is also stored untraced, in the variable named $2
# shellcheck disable=SC2034  # the namerefs are written for the caller
pcrlock_make_policy()
{
	local -; set +x
	local pmp_pin_name="$1"
	local -n pmp_output="$2"
	shift 2
	pmp_output="$(run_with_secret PIN "$pmp_pin_name" pcrlock "$@" make-policy 2>"$tmpfile")"
}

# Show the recovery PIN that `make-policy` made, if the output in the
# variable named $1 has one.  Add it to the kernel keyring, so that
# `sdbootutil enroll --method=recovery-key` can use it
show_generated_recovery_pin()
{
	local -; set +x
	local -n sgrp_output="$1"
	local sgrp_split sgrp_pin
	echo "$sgrp_output" | grep -q "recovery PIN" || return 1
	IFS=":" read -r -a sgrp_split <<<"$sgrp_output"
	sgrp_pin="${sgrp_split[1]}"
	sgrp_pin="${sgrp_pin## }"
	sgrp_pin="${sgrp_pin%% }"

	echo "Recovery PIN: $sgrp_pin"
	if command -v qrencode > /dev/null; then
		echo "You can also scan it with your mobile phone:"
		echo -n "$sgrp_pin" | qrencode -t utf8i
	fi

	keyctl_add_with_timeout "sdbootutil-recovery-pin" sgrp_pin
}

# The components that `systemd-pcrlock` removes when it is asked over
# varlink (io.systemd.PCRLock.Lock), by category of the method.  Each
# value is the first file that it removes.  systemd fixes the
# categories, not fwupd.  tests/unit checks them against the installed
# systemd-pcrlock
declare -gA pcrlock_unlockable=(
	[firmwareCode]=250-firmware-code-early
	[firmwareConfig]=250-firmware-config-early
	[secureBootPolicy]=240-secureboot-policy
	[secureBootAuthority]=620-secureboot-authority
)

pcrlock_unlocked()
{
	grep -qsFx "$1" /run/sdbootutil/pcrlock-unlocked
}

# fwupd prepares a firmware update in two steps.  It asks
# `systemd-pcrlock` to remove the components that the update will
# change.  Then it asks for a new policy without them.  This function
# runs after every connection to the systemd-pcrlock service (the
# systemd-pcrlock@.service drop-in).  It makes that policy one of ours:
#
#  - The service keeps the PCRs of the current policy.  But the
#    initrd imports the policy from the ESP, and the new policy is
#    only in /var/lib/systemd.
#
#  - The components are made from the event log of this boot.  So
#    `update-predictions` would bring back the old measurements
#    before the update is applied.  They stay out until the next
#    boot (the list is in /run).  Then the boot service locks them
#    again from the new event log
sync_pcrlock_policy()
{
	# Only for a policy that sdbootutil published
	[ -e "${esp_root}${esp_dst}/pcrlock.json" ] || return 0
	[ -e /var/lib/systemd/pcrlock.json ] || return 0

	# A component can also be missing because sdbootutil could not
	# make it in this boot.  It is fine to skip it until the next
	# boot.  It would fail again, because the event log is the same
	local component unlocked=() previous=()
	for component in "${pcrlock_unlockable[@]}"; do
		[ -e "/var/lib/pcrlock.d/$component.pcrlock.d/generated.pcrlock" ] || unlocked+=("$component")
	done

	# When the update fails, fwupd puts the components back and
	# makes a new policy.  That policy uses the PCRs of the current
	# one, so the PCRs dropped before are still missing.  The next
	# boot would unlock without them.  So our own policy, with all
	# the PCRs, replaces it
	[ ! -e /run/sdbootutil/pcrlock-unlocked ] || mapfile -t previous < /run/sdbootutil/pcrlock-unlocked
	for component in "${previous[@]}"; do
		[[ " ${unlocked[*]} " == *" $component "* ]] || update_predictions=1
	done

	if [ "${#unlocked[@]}" -gt 0 ]; then
		printf '%s\n' "${unlocked[@]}" > /run/sdbootutil/pcrlock-unlocked
	else
		rm -f /run/sdbootutil/pcrlock-unlocked
	fi

	! cmp -s /var/lib/systemd/pcrlock.json "${esp_root}${esp_dst}/pcrlock.json" || return 0

	# See `generate_tpm2_predictions_pcrlock` for the credential
	rm -f "${boot_root}/loader/credentials/pcrlock.${entry_token}.cred"
	cp /var/lib/systemd/pcrlock.json "${esp_root}${esp_dst}" || \
		err "Cannot copy the pcrlock policy into the ESP"
	info "Published the pcrlock policy made by systemd-pcrlock${unlocked[*]:+, without ${unlocked[*]} until the next boot}"
}

# Whether the next boot is a UKI boot.  It is when the UKIs are selected
# and there are UKI entries to predict (see
# `select_entries_for_prediction`)
next_boot_uki()
{
	uki_selected && jq -e 'any(.[]; .uki)' "$entryfile" > /dev/null
}

# Whether the next boot is of another kind than this one.  There are two
# kinds.  A UKI boot is started by systemd-stub ("measured-os").  The
# other kind boots a kernel and an initrd
boot_kind_changes()
{
	local next="" this=""
	if next_boot_uki; then
		next=1
	fi
	if systemd-analyze condition 'ConditionSecurity=measured-os' &> /dev/null; then
		this=1
	fi
	[ "$next" != "$this" ]
}

# systemd measures "os-separator" into PCRs 0-7, 9 and 12-14 when
# systemd-stub starts the kernel ("measured-os").  So this only happens
# on UKI boots, before the devices are unlocked.  When the next boot is
# of another kind than this one, the component gets a second, empty
# variation, next to the one of the system.  Then the policy accepts
# this boot and the next one.  pcrlock joins the file of the system and
# this directory in one component
os_separator_variations()
{
	local dir=/var/lib/pcrlock.d/750-os-separator.pcrlock.d
	local mask=/var/lib/pcrlock.d/750-os-separator.pcrlock
	# Left from an earlier run in this boot.
	# `mask_unmatched_components` masks it again when the event log
	# does not have it
	rm -rf "$dir"
	[ ! -e "$mask" ] || [ -s "$mask" ] || rm -f "$mask"
	boot_kind_changes || return 0
	info "The next boot is of another kind than this one (a UKI or not), predicting it with and without the os-separator"
	mkdir -p "$dir"
	# The name sorts after the others, see systemd#36436
	echo '{"records": []}' > "$dir/zz-none.pcrlock"
}

generate_tpm2_predictions_pcrlock()
{
	local pcrs="$FDE_SEAL_PCR_LIST"

	info "Generating TPM2 predictions"

	# Select the affected entries
	select_entries_for_prediction

	# The kernel measures into PCR 9 the initrd that systemd-stub
	# passes to it.  This is the .initrd of the UKI and the cpio
	# archives that the stub makes.  One archive has the "boot
	# secret".  The secret is unknown before the first boot of a
	# UKI, and the archives use internal formats of the stub.  So
	# PCR 9 is not predicted for a UKI.  The signed PCR 11 policy
	# covers the initrd and the command line of the UKI instead.
	# The rule is the same as in `select_entries_for_prediction`:
	# PCR 9 is left out while the UKIs are selected and there are
	# UKI entries to predict.  When the UKIs are no longer selected,
	# PCR 9 is back in the policy
	if [[ ",$pcrs," == *",9,"* ]] && next_boot_uki; then
		info "The UKIs are selected, PCR 9 is left out of the policy"
		pcrs="$(remove_pcr "$pcrs" 9)"
		[ -z "$arg_strict" ] || \
			err "PCR 9 cannot be predicted for the UKIs, so it cannot be part of the policy. No policy is applied, run without --strict to accept the subset"
	fi

	# Save the components as they were, for `verify_esp_files`
	rm -rf "$tmpdir/pcrlock.d"
	[ ! -d /var/lib/pcrlock.d ] || cp -R /var/lib/pcrlock.d "$tmpdir/pcrlock.d"
	clean_pcrlock_d
	os_separator_variations
	rm -f "$tmpdir/esp-files"

	# A component that fwupd unlocked before a firmware update (see
	# `sync_pcrlock_policy`) stays out until the next boot
	if ! pcrlock_unlocked 250-firmware-code-early; then
		shift_component 250-firmware-code-early
		shift_component 550-firmware-code-late
		pcrlock_lock lock-firmware-code
	fi

	if ! pcrlock_unlocked 250-firmware-config-early; then
		shift_component 250-firmware-config-early
		shift_component 550-firmware-config-late
		pcrlock_lock lock-firmware-config
	fi

	if ! pcrlock_unlocked 240-secureboot-policy; then
		shift_component 240-secureboot-policy
		pcrlock_lock lock-secureboot-policy
	fi

	if ! pcrlock_unlocked 620-secureboot-authority; then
		shift_component 620-secureboot-authority
		pcrlock_lock lock-secureboot-authority
		# `pcrlock_secureboot_sbatlevel` makes
		# 620-secureboot-authority when the verb cannot
		pcrlock_secureboot_sbatlevel
	fi

	# `lock-gpt` uses / by default.  But the firmware measures the
	# GPT of the disk that the boot application was loaded from.
	# That is the disk of our ESP
	shift_component 600-gpt
	pcrlock lock-gpt "$esp_root"

	# Measure the boot loader.  Combinations:
	#   - Removable media with shim: BOOTX64.EFI, grub.efi
	#   - Removable media w/out shim: BOOTX64.EFI
	#   - Installed system with shim: shim.efi, grub.efi
	#   - Installed system w/out shim and grub2-bls: grub.efi
	#   - Installed system w/out shim and systemd-boot: systemd-bootx64.efi
	local shim_path bootloader_path
	if is_shim_installed; then
		if [ -n "$arg_portable" ]; then
			shim_path="${esp_root}/EFI/BOOT/BOOT${firmware_arch^^}.EFI"
			bootloader_path="${esp_root}/EFI/BOOT/grub.efi"
		else
			shim_path="${esp_root}${esp_dst}/shim.efi"
			bootloader_path="${esp_root}${esp_dst}/grub.efi"
		fi
	else
		local bootloader_filename
		if is_sdboot; then
			bootloader_filename="systemd-boot${firmware_arch,,}.efi"
		elif is_grub2_bls; then
			bootloader_filename="grubbls.efi"
		fi
		if [ -n "$arg_portable" ]; then
			bootloader_path="${esp_root}/EFI/BOOT/BOOT${firmware_arch^^}.EFI"
		else
			bootloader_path="${esp_root}${esp_dst}/${bootloader_filename}"
		fi
	fi

	if [ -n "$shim_path" ]; then
		# 630-shim-efi-application is not part of the pcrlock
		# standards
		# TODO: move to shim-pcrlock.rpm
		shift_component 630-shim-efi-application
		track_esp_file "${shim_path}"
		pcrlock \
			lock-pe \
			--pcrlock=/var/lib/pcrlock.d/630-shim-efi-application.pcrlock.d/generated.pcrlock \
			"${shim_path}"
	fi

	# 640-boot-loader-efi-application is not part of the pcrlock
	# standards.  It measures the grub or systemd-boot EFI binary
	# TODO: move to systemd-boot-pcrlock.rpm / grub2-bls.rpm
	shift_component 640-boot-loader-efi-application
	track_esp_file "${bootloader_path}"
	pcrlock \
		lock-pe \
		--pcrlock=/var/lib/pcrlock.d/640-boot-loader-efi-application.pcrlock.d/generated.pcrlock \
		"${bootloader_path}"

	if is_sdboot; then
		pcrlock_sdboot
	elif is_grub2_bls; then
		pcrlock_grub2_bls
	fi

	prune_pcrlock_cache

	# Nothing that sdbootutil did not install can reach the policy
	verify_esp_files

	restore_shifts

	# `dracut-pcr-signature` imports the copy in the ESP.  This copy
	# can be missing after a new ESP installation.  Both copies are
	# the same, so a missing one is restored from the other.  This
	# alone does not need a new policy.
	#
	# The local copy matters too, because it stores the PIN that
	# `systemd-pcrlock` needs to update the NVIndex.  Without it, a
	# new policy cannot replace the current one
	if [ -e /var/lib/systemd/pcrlock.json ] && [ ! -e "${esp_root}${esp_dst}/pcrlock.json" ]; then
		dbg "Restoring the pcrlock policy in the ESP"
		cp /var/lib/systemd/pcrlock.json "${esp_root}${esp_dst}" || \
			warn "Cannot copy the pcrlock policy into the ESP"
	elif [ ! -e /var/lib/systemd/pcrlock.json ] && [ -e "${esp_root}${esp_dst}/pcrlock.json" ]; then
		dbg "Restoring the pcrlock policy from the ESP"
		cp "${esp_root}${esp_dst}/pcrlock.json" /var/lib/systemd/ || \
			warn "Cannot restore the pcrlock policy from the ESP"
	fi

	# Decide if the current policy can be kept.  Do it before any
	# expensive step (`predict` and `make-policy`), and before
	# asking for any PIN.
	#
	# The hashes that can be part of the policy are compared with
	# the hashes used to build the current policy.  They are not
	# compared with the hashes from before the components were made
	# again.  This is because
	# `sdbootutil-update-predictions.service` also makes the
	# components at boot.  So a firmware change is already in
	# `/var/lib/pcrlock.d` before the user can run this command.
	# Comparing with the state of this run would hide such a change
	# forever, and only wiping `/var/lib/pcrlock.d` would fix it.
	#
	# Repeated hashes add no new values, so the list has no
	# duplicates
	local post_hashes
	post_hashes="$(get_predicted_hashes)"

	# A PCR that cannot be predicted is dropped from the policy.
	# The reason is often temporary: it is about the current event
	# log, and the next boot fixes it.  The components do not need
	# to change for that.  So with the hashes alone, the smaller
	# policy would be kept forever
	local missing_pcrs extra_pcrs
	missing_pcrs="$(policy_missing_pcrs "$pcrs")"
	extra_pcrs="$(policy_extra_pcrs "$pcrs")"

	if [ -n "$arg_force" ]; then
		dbg "A new policy is forced (--force)"
	elif [ ! -e /var/lib/systemd/pcrlock.json ]; then
		# There is no policy to keep, whatever the components
		# are
		dbg "Missing /var/lib/systemd/pcrlock.json"
	elif [ ! -e /var/lib/sdbootutil/pcrlock-hashes ]; then
		# The policy was made by a version that did not track
		# the hashes, so there is nothing to compare with.
		# `make-policy` will see that the prediction is the
		# same, and will not touch the NVIndex
		dbg "Missing /var/lib/sdbootutil/pcrlock-hashes"
	elif ! echo "$post_hashes" | cmp -s - /var/lib/sdbootutil/pcrlock-hashes; then
		dbg "The components changed since the current policy was created"
	elif [ -n "$missing_pcrs" ]; then
		dbg "The current policy does not cover the requested PCR $missing_pcrs"
	elif [ -n "$extra_pcrs" ]; then
		dbg "The current policy binds the PCR $extra_pcrs, no longer requested"
	else
		info "Policy is up to date"
		return 0
	fi

	# shim raises `SbatLevel` to the level built into its binary,
	# and measures it into PCR 7 before the volume is unlocked.
	# When the shim in the ESP did not make the current event log,
	# the new value is unknown here.  So PCR 7 is left out of this
	# policy.  `sdbootutil-update-predictions.service` adds it back
	# on the next boot, when the event log has the measurement
	if [[ ",$pcrs," == *",7,"* ]] && shim_changed; then
		info "The shim in the ESP is a new one, PCR 7 is left out until the next boot"
		pcrs="$(remove_pcr "$pcrs" 7)"

		# `--strict` asks for all the requested PCRs or none
		[ -z "$arg_strict" ] || \
			err "The next SbatLevel measurement cannot be predicted, so PCR 7 cannot be part of the policy. No policy is applied, run without --strict to accept the subset"
	fi

	local final_pcrs
	final_pcrs="$(get_final_pcrs "$pcrs")" || return 1

	# If the prediction fails, the system asks for a password at
	# boot.  Then the recovery PIN can be used to enroll again.  To
	# register a recovery PIN, the installer (sdbootutil-enroll,
	# YaST) calls this script with the "sdbootutil-recovery-pin"
	# entry in the %u keyring (or the deprecated "sdbootutil-pin"
	# and "sdbootutil" entries).  To enroll again, use the same
	# entry, the RECOVERY_PIN or PIN environment variables, or the
	# --ask-recovery-pin parameter.
	local pin
	local extra=()
	recovery_pin_for_policy pin extra

	# Rewrite the NV index even when systemd-pcrlock sees no change
	# in the prediction
	[ -z "$arg_force" ] || extra+=("--force")

	# `systemd-pcrlock` skips the update when the new prediction is
	# the same as the one in the current policy.  It does this
	# before it authenticates against the TPM2.  So the recovery PIN
	# is never used, and a wrong one is accepted without a word.
	# The policy file is written only when the NVIndex is updated.
	# So the file tells both cases apart
	local policy_digest=
	[ ! -e /var/lib/systemd/pcrlock.json ] || \
		policy_digest="$(sha256sum < /var/lib/systemd/pcrlock.json)"

	# As in `get_final_pcrs`, the status is read in the same
	# command.  A separate line would not work: `set -e` would end
	# the script there, without printing the reason that
	# `systemd-pcrlock` left in $tmpfile
	local output
	local pcrlock_status=0
	pcrlock_make_policy pin output --pcr="$final_pcrs" "${extra[@]}" || pcrlock_status=$?

	# `make-policy` also writes the policy as a credential.
	# systemd-stub passes it to the initrd of every UKI.  It is
	# measured into PCR 9 and PCR 12, and a policy cannot predict
	# its own digest.  So neither PCR could be sealed for a UKI.
	# Instead, the initrd gets the policy from the ESP
	# (dracut-pcr-signature).  There is no option to skip the
	# credential, so it is removed here
	rm -f "${boot_root}/loader/credentials/pcrlock.${entry_token}.cred"

	# `systemd-pcrlock` explains on stderr what it did.  The
	# messages are lost when the command succeeds, so they are shown
	# here in debug mode
	dbg_cat "$tmpfile"

	if [ "$pcrlock_status" -ne 0 ]; then
		warn "Error creating the systemd-pcrlock policy!\n$(cat "$tmpfile")"
		explain_pcrlock_policy_error "$tmpfile" pin
		return 1
	elif show_generated_recovery_pin output; then
		# A recovery key that is already in the LUKS2 header was
		# made equal to the recovery PIN of that time.
		# `enroll_recovery_key` says so when it enrolls it.
		# This PIN is a new one, so from now on they are two
		# different secrets.  The value printed above is the
		# only copy of the new PIN
		local rdev
		for rdev in "${tracked_devices[@]}"; do
			have_slot "$rdev" "recovery" || continue
			warn "There is already a recovery key for $rdev"
			warn "The recovery key and the recovery PIN are now different"
			break
		done
	fi

	[ -e /var/lib/systemd/pcrlock.json ] || {
		warn "Missing /var/lib/systemd/pcrlock.json after the policy creation"
		return 1
	}

	# Track the hashes used for this policy, so a later run can
	# detect that the components diverged from it
	echo "$post_hashes" > /var/lib/sdbootutil/pcrlock-hashes

	# Publish the policy in the ESP, so that dracut-pcr-signature
	# can import it
	cp /var/lib/systemd/pcrlock.json "${esp_root}${esp_dst}" || \
		warn "Cannot copy the pcrlock policy into the ESP"

	# With --force the NVIndex is always written, but the policy
	# file can still be the same.  The serializations of the
	# NVIndex, the SRK and the sealed PIN are reused from the old
	# policy.  Only the prediction can make the file different
	if [ -n "$arg_force" ] || \
	    [ "$policy_digest" != "$(sha256sum < /var/lib/systemd/pcrlock.json)" ]; then
		echo "NVIndex policy created"
	else
		info "The prediction did not change, so the NVIndex was not updated"
		# Only the TPM2 can tell if the recovery PIN is correct.
		# It checks the PIN when the NVIndex is written.
		# Without this message, a wrong PIN looks accepted,
		# because the command succeeds
		[ -z "${pin:+set}" ] || \
			warn "The recovery PIN was not needed, so it was not validated. Use --force to rewrite the NVIndex with it"
	fi
}

# Whether the password in the variable named $2 opens the device $1
valid_password()
{
	local -; set +x
	local vp_dev="${1:?}"
	local -n vp_pw="$2"

	[ -n "$vp_pw" ] || return 1
	# Without --disable-external-tokens, an enrolled TPM2 or FIDO2
	# token opens the device, and any password looks valid
	cryptsetup luksOpen --test-passphrase --disable-external-tokens "$vp_dev" <<<"$vp_pw" &> /dev/null
}

# Find a password that opens the device.  Store it in $device_pw (empty
# if there is none) and in %user:cryptenroll.  It is a global and not
# the output, so that the caller does not trace it in an assignment
get_device_password()
{
	local -; set +x
	local dev="${1:?}"
	local pw='' keyid candidate
	local from_keyring=()
	local candidates=()

	# %user:cryptenroll is read first.  systemd-cryptenroll reads it
	# by itself, so when it already opens the device there is
	# nothing to add.  It can hold several passwords, one per
	# device, separated by NUL
	if keyid="$(keyctl id %user:cryptenroll 2> /dev/null)"; then
		mapfile -d '' -t from_keyring < <(keyctl pipe "$keyid")
	fi

	# CURRENT_PW is the only source that says it holds the *current*
	# password, so it is tried first
	[ -z "$env_current_pw" ] || candidates+=("$env_current_pw")

	# PW, KEY, RECOVERY_PIN and the %user:sdbootutil* entries hold
	# the *new* secret for the password, recovery-key and tpm2+pin
	# methods.  During the first enrollment they can hold the
	# recovery PIN, which is then also the recovery key.  So every
	# candidate is checked before it is used.  Adding a wrong one is
	# not harmless: keyctl replaces the payload, so a valid password
	# would be lost.  Because of this check, %user:sdbootutil is not
	# ambiguous here, and it is not deprecated as a candidate
	[ -z "$env_pw" ] || candidates+=("$env_pw")
	[ -z "$env_key" ] || candidates+=("$env_key")
	[ -z "$env_recovery_pin" ] || candidates+=("$env_recovery_pin")
	local name
	for name in sdbootutil-pw sdbootutil-key sdbootutil-recovery-pin sdbootutil-pin sdbootutil; do
		if keyid="$(keyctl id %user:"$name" 2> /dev/null)"; then
			candidates+=("$(keyctl pipe "$keyid")")
		fi
	done

	# Each wrong candidate costs one Argon2 per keyslot, and the
	# sources often hold the same value.  So each value is tried
	# only once
	local in_keyring=
	local -A tried=()
	for candidate in "${from_keyring[@]}"; do
		[ -n "$candidate" ] || continue
		tried["$candidate"]=1
		valid_password "$dev" candidate || continue
		pw="$candidate"
		in_keyring=1
		break
	done
	if [ -z "$pw" ]; then
		for candidate in "${candidates[@]}"; do
			[ -n "$candidate" ] && [ -z "${tried["$candidate"]+set}" ] || continue
			tried["$candidate"]=1
			valid_password "$dev" candidate || continue
			pw="$candidate"
			break
		done
	fi

	# Ask for the password only as a last resort, and only with
	# --ask-current-pw.  Any other --ask-* option also means that
	# someone is at a terminal and can type it
	if [ -z "$pw" ] && [ -n "$arg_ask_key$arg_ask_pin$arg_ask_recovery_pin$arg_ask_pw$arg_ask_current_pw" ]; then
		ask_password "Password for $dev" pw
		valid_password "$dev" pw || {
			warn "The password does not unlock $dev"
			pw=''
		}
	fi

	if [ -n "$pw" ] && [ -z "$in_keyring" ]; then
		keyctl_add_with_timeout "cryptenroll" pw
	fi

	device_pw="$pw"
}

# jq definitions for the tokens of a LUKS2 header.  "pcrlock" is a
# pcrlock TPM2 slot.  "bound" is bound to PCR 15.  "pin" has a PIN.
# "signed" has a signed PCR policy (the policy of the UKIs, next to
# pcrlock)
jq_tpm2_token_defs='
	def pcrlock: .type == "systemd-tpm2" and (.tpm2_pcrlock // false);
	def bound: (.["tpm2-pcrs"] // []) | index(15) != null;
	def pin: .["tpm2-pin"] // false;
	def signed: has("tpm2_pubkey");
'

# systemd-cryptsetup tries the LUKS2 tokens by itself.  So a TPM2 slot
# still opens the device when /etc/crypttab does not ask for it.  But
# then nothing updates its policy: `generate_tpm2_predictions` and the
# boot service both look for "tpm2-device" in /etc/crypttab.  The slot
# works until the next change of a sealed PCR.  Then the boot asks for
# the password.  Only the pcrlock policy needs the update.  A signed
# policy does not
has_pcrlock_slot()
{
	luks_header "${1:?}" | jq -e "$jq_tpm2_token_defs"'any(.tokens[]?; pcrlock)' > /dev/null
}

warn_tpm2_slot_without_option()
{
	local dev
	detect_tracked_devices || return 0
	for dev in "${tracked_devices[@]}"; do
		has_pcrlock_slot "$dev" || continue
		warn "$dev has a TPM2 slot, but no \"tpm2-device\" option in /etc/crypttab, so its TPM2 policy is never updated"
		warn "Add \"tpm2-device=auto\" to /etc/crypttab and call 'sdbootutil update-predictions', or enroll it again"
	done
}

generate_tpm2_predictions()
{
	[ -e /etc/crypttab ] || return 0
	grep -q "^[^#]*tpm2-device" /etc/crypttab || { warn_tpm2_slot_without_option; return 0; }
	! in_lockout || err "The TPM2 is in lockout. Use 'tpm2_dictionarylockout -c [ -p passwd ]' to clear the DA lockout and re-try the sdbootutil command"

	info "Updating predictions"

	[ -z "$TRANSACTIONAL_UPDATE" ] || [ -n "$arg_force" ] || {
		warn "Inside transactional-update. Updating predictions must be done outside the transaction"
		return 0
	}

	[ -z "${DEVICETREE_SOURCE:-}" ] || ! is_sdboot || {
		warn "TPM2 predictions with systemd-boot devicetree entries are not validated. Use --disable-predictions if this affects boot."
	}

	! is_pcr_oracle || {
		warn "System enrolled with pcr-oracle. Re-enroll to use systemd-pcrlock"
		return 0
	}

	# `is_pcr_oracle` is false once the pcr-oracle package is gone.  But
	# the LUKS2 token can still require a signed PCR policy, and nothing
	# signs it anymore.  Then the pcrlock predictions are updated, but the
	# TPM2 unlock keeps falling back to the password.  Only a
	# re-enrollment fixes that
	local dev
	if detect_tracked_devices; then
		for dev in "${tracked_devices[@]}"; do
			! has_signed_pcr_policy "$dev" || \
				warn "$dev is enrolled with a signed PCR policy. Re-enroll to use systemd-pcrlock"
		done
	fi

	# PCR 15 is bound in the TPM2 slots, not in the policy (see
	# `pcr15_slot_value`).  Older versions described PCR 15 with these
	# components.  Remove them, and the files that tracked them
	rm -fr /var/lib/pcrlock.d/790-volume-key-*.pcrlock.d \
	       /var/lib/pcrlock.d/795-leave-initrd.pcrlock \
	       /var/lib/sdbootutil/crypttab.sha1

	generate_tpm2_predictions_pcrlock

	# This warning comes only after the policy is good.
	# `generate_tpm2_predictions_pcrlock` leaves the script when it fails.
	# In that case `explain_pcrlock_policy_error` already talks about the
	# missing PIN.  Here the warning also covers the exit with "Policy is
	# up to date".  That exit is the common one, and without this warning
	# nothing would be said
	warn_no_recovery_pin

	# The policy that was just written covers the entry that the boot
	# loader selects, so the machine still unlocks.  But when the default
	# snapshot and the default entry diverge, one of the few slots is
	# spent on a snapshot that nothing is going to boot.  grub2-bls has
	# only two slots
	warn_default_snapshot_diverged
}

have_tracked_devices()
{
	[ "${#tracked_devices[@]}" -gt 0 ]
}

# A LUKS2 device is managed by sdbootutil when /etc/crypttab has a line
# for it, unless that line carries the "x-sdbootutil.ignore" option.
#
# The question is which crypttab line describes this device.
# `is_same_device` answers it, the same way as in `add_crypttab_option`.
# Searching the file for the name of the device is wrong in four ways.
# First, the match is not anchored to the device field, so a mention
# inside a comment counts.  Second, "." and "-" in a path are regular
# expression syntax.  Third, "/dev/sda2" is found in "/dev/sda21".
# Fourth, a line that names the device by "PARTUUID=", "LABEL=" or
# "PARTLABEL=" is not found at all.  That silently leaves the device
# unmanaged
is_tracked_device()
{
	local dev="${1:?}"
	local name device key opts

	# With no crypttab, nothing can exclude the device, and nothing can
	# name it either
	[ -e /etc/crypttab ] || return 0

	while read -r name device key opts; do
		[[ "$name" != \#* ]] || continue
		[ -n "$name" ] || continue
		is_same_device "$dev" "$device" || continue
		[[ "$opts" != *"x-sdbootutil.ignore"* ]] || {
			dbg "Ignoring encrypted device $dev, un-tracked in /etc/crypttab"
			return 1
		}
		return 0
	done < /etc/crypttab

	dbg "Ignoring encrypted device $dev, absent from /etc/crypttab"
	return 1
}

# The anchor: the device that measures its volume key into PCR 15.  It
# is the first tracked device behind the root file system (a btrfs can
# span several devices).  It is unlocked first.  Its slots are bound to
# PCR 15 while PCR 15 is still zero, so they only unseal in the initrd.
# "Tracked" means the same as in `detect_tracked_devices`, but
# --devices does not limit it.  This is because the anchor is a
# property of the boot
measure_anchor()
{
	local uuid path dev fstype
	read -r uuid < <(findmnt / -v -n -o UUID 2> /dev/null)
	[ -n "$uuid" ] || return 1
	while read -r path; do
		while read -r dev fstype; do
			[ "$fstype" = 'crypto_LUKS' ] || continue
			cryptsetup isLuks --type luks2 "$dev" || continue
			is_tracked_device "$dev" || continue
			echo "$dev"
			return 0
		done < <(lsblk --noheadings --list --inverse -o PATH,FSTYPE "$path" 2> /dev/null)
	done < <(lsblk --noheadings --list -o PATH -Q "UUID == \"$uuid\"" 2> /dev/null)
	return 1
}

# The value of PCR 15 once the anchor "$1" is measured.  With "$2" set
# to leave-initrd, the value after the end of the initrd too.  The
# value is taken from the measurement log of this boot.  The digest is
# the one that systemd-cryptsetup computed from the volume key, so
# sdbootutil never reads the volume key.  Fails when the anchor was not
# measured in the initrd of this boot.  Also fails when the log does
# not explain the current PCR 15
pcr15_bound_value()
{
	local anchor="${1:?}"
	local phase="$2"
	local log=/run/log/systemd/tpm2-measure.log
	local uuid digest

	[ -r "$log" ] || return 1
	uuid="$(cryptsetup luksUUID "$anchor" 2> /dev/null)" || return 1

	[ "$(pcr15_events "$log" "" | pcr15_replay)" = \
	  "$(systemd-analyze pcrs 15 --json=short 2> /dev/null | jq -r '.[0].sha256')" ] || return 1

	# The log is RFC 7464 JSON-seq, see `pcr15_events`
	digest="$(tr -d '\036' < "$log" | \
		  jq -rs --arg uuid "$uuid" \
		     '[.[] | select(.pcr == 15)] as $r
		      | ($r | map(.content.eventType == "phase") | index(true)) as $leave
		      | ($r | map(.content.eventType == "volume-key" and (.content.string | endswith(":" + $uuid))) | index(true)) as $i
		      | select($i != null and ($leave == null or $i < $leave))
		      | $r[$i].digests[] | select(.hashAlg == "sha256") | .digest' 2> /dev/null)"
	[ -n "$digest" ] || return 1

	{
		echo "$digest"
		[ -z "$phase" ] || echo -n "$phase" | sha256sum | cut -d' ' -f1
	} | pcr15_replay
}

# The /etc/crypttab inside the initrd of the default entry.  dracut
# copies there the devices that the initrd unlocks.  These are not only
# the ones marked x-initrd.attach (the resume device is one example).
# `read_initrd_crypttab` reads it into "initrd_crypttab_cache" once per
# run, as reading it means decompressing the initrd
initrd_crypttab_cache=
initrd_crypttab_read=
read_initrd_crypttab()
{
	[ -z "$initrd_crypttab_read" ] || return 0
	initrd_crypttab_cache="$(initrd_crypttab)" || initrd_crypttab_cache=
	initrd_crypttab_read=1
}

# Whether the initrd unlocks "$1".  Call `read_initrd_crypttab` first
in_initrd_crypttab()
{
	local dev="${1:?}" name device _
	while read -r name device _; do
		[[ "$name" != \#* ]] || continue
		[ -n "$name" ] || continue
		! is_same_device "$dev" "$device" || return 0
	done <<<"$initrd_crypttab_cache"
	return 1
}

# The crypttab in the initrd of the addons FILE... of an entry.  Only
# the addon of the root has one (see `update_dps_addon`)
addons_crypttab()
{
	local file
	for file; do
		objcopy -O binary --only-section=.initrd "$boot_root$file" "$tmpdir/addon-initrd" 2> /dev/null || continue
		[ ! -s "$tmpdir/addon-initrd" ] || cpio --quiet -i --to-stdout etc/crypttab < "$tmpdir/addon-initrd" 2> /dev/null
	done
	rm -f "$tmpdir/addon-initrd"
}

# The jq filter that lists the files of an entry with an initrd, in one
# line.  First the initrd, or the UKI (lsinitrd reads the initrd inside
# it), then the addons
# shellcheck disable=SC2016  # jq
jq_initrd_files='[.initrd[0] // .uki // empty] + [.addons[]? | .globalAddon // .localAddon] | join("\t")'

initrd_crypttab()
{
	local id files=()
	update_entries_for_this_system
	id="$(get_default_entry)"
	IFS=$'\t' read -r -a files < <(jq -r --arg id "$id" '.[] | select(.id == $id or .id == $id + ".conf") | '"$jq_initrd_files" < "$entryfile" | head -n 1)
	[ -n "${files[0]:-}" ] && [ -e "$boot_root${files[0]}" ] || return 1
	# The initrd of an addon is loaded after the one of the entry, so the
	# crypttab of the addon is the one in effect
	local crypttab
	crypttab="$(addons_crypttab "${files[@]:1}")"
	if [ -n "$crypttab" ]; then
		echo "$crypttab"
	else
		lsinitrd -f etc/crypttab "$boot_root${files[0]}" 2> /dev/null
	fi
}

# Where the device "$1" is opened, with the anchor "$2".  "anchor" is
# the anchor itself.  "initrd" is a device that the initrd opens after
# the anchor.  "late" is a device that is opened after the end of the
# initrd.  The caller runs `read_initrd_crypttab` first
device_stage()
{
	if [ "${1:?}" = "${2:-}" ]; then
		echo anchor
	elif in_initrd_crypttab "$1"; then
		echo initrd
	else
		echo late
	fi
}

# The value of PCR 15 that the TPM2 slot of "$1" is bound to, with the
# anchor "$2".  The caller runs `read_initrd_crypttab` first, in its own
# shell.  This is because this function usually runs in a subshell
#
# PCR 15 is zero until the anchor measures its volume key.
# leave-initrd changes it again before switching root.  So the slot of
# the anchor never unseals once the initrd is gone.  The other devices
# unlock after the anchor, so their slots are bound to PCR 15 after the
# anchor is measured.  For the devices that the initrd opens, this is
# the value in the initrd.  For the other devices, it is the value
# after the end of the initrd
pcr15_slot_value()
{
	local dev="${1:?}" anchor="${2:?}"

	case "$(device_stage "$dev" "$anchor")" in
		anchor) printf '%064d\n' 0 ;;
		initrd) pcr15_bound_value "$anchor" "" ;;
		late) pcr15_bound_value "$anchor" leave-initrd ;;
	esac
}

# Whether the TPM2 slot of "$1" has no PCR 15, with the anchor "$2".
# This is the case with the UKIs, for a device that the initrd does not
# unlock.  On UKI boots, the machine ID and the file systems are
# measured into PCR 15 after the initrd.  Nothing orders these
# measurements with these devices.  The pcrlock policy still pins the
# boot, the whole UKI included.  The caller runs `read_initrd_crypttab`
# first
pcr15_unbound_device()
{
	uki_selected && [ "$(device_stage "${1:?}" "${2:-}")" = late ]
}

# The arguments of systemd-cryptenroll for the signed PCR policy of the
# TPM2 slot of "$2", with the anchor "$3".  They go into the array
# named "$1".  With the UKIs, the devices unlocked in the initrd get the
# signed PCR 11 policy.  This is because the signatures are for the
# enter-initrd phase.  Otherwise there is no signed policy, but an empty
# --tpm2-public-key is still passed.  Without it, systemd-cryptenroll
# would load a tpm2-pcr-public-key.pem from the configuration
# directories.  Fails when the key is missing
uki_public_key_args()
{
	local -n upka_args="$1"
	local key
	upka_args=(--tpm2-public-key=)
	uki_selected && ! pcr15_unbound_device "$2" "${3:-}" || return 0
	key="$(uki_pcr_public_key)" || return 1
	# shellcheck disable=SC2034  # nameref
	upka_args=(--tpm2-public-key="$key" --tpm2-public-key-pcrs=11 --tpm2-public-key-policyref=initrd)
}

# How the pcrlock TPM2 slots of "$1" are bound.  "$2" is the LUKS2
# header, if the caller has it.  "bound" means that a slot is bound to
# PCR 15.  "bound+plain" means that an unbound slot is still there too.
# "plain" means that a slot is not bound and has no PIN.  "pin" means
# that all the slots need a PIN.  "none" means that there is no pcrlock
# slot
tpm2_slot_binding()
{
	local header="${2:-}"
	[ -n "$header" ] || header="$(luks_header "${1:?}")"
	jq -r "$jq_tpm2_token_defs"'
		[.tokens[] | select(pcrlock)] as $t
		| ($t | map(select(bound)) | length) as $bound
		| ($t | length) as $all
		| if $bound > 0 and $all > $bound then "bound+plain"
		  elif $bound > 0 then "bound"
		  elif ($t | map(select(pin | not)) | length) > 0 then "plain"
		  elif $all > 0 then "pin"
		  else "none" end' <<<"$header"
}

# The names in a crypttab read from stdin, sorted
crypttab_names()
{
	local name _
	while read -r name _; do
		[[ "$name" != \#* ]] || continue
		[ -z "$name" ] || echo "$name"
	done | sort
}

# Whether every boot entry of this system boots an initrd that unlocks
# the devices the way the bound slots expect.  "$1" is the crypttab
# name of the anchor.  The anchor must measure alone.  The other
# devices must unlock after it.  The end of the initrd must be
# measured.  The initrd must have the same devices as the initrd of the
# default entry.  This is because that initrd decided which slots are
# bound in the initrd and which after it.  Until all this is true, a
# rollback needs the unbound slots
entries_bind_pcr15()
{
	local anchor="${1:?}" initrd dir name _ opts expected names files=() crypttab
	local -A unpacked=()

	read_initrd_crypttab
	expected="$(crypttab_names <<<"$initrd_crypttab_cache")"
	update_entries_for_this_system
	while IFS=$'\t' read -r -a files; do
		initrd="${files[0]:-}"
		[ -n "$initrd" ] && [ -e "$boot_root$initrd" ] || return 1
		# Decompress each initrd only once, as the entries of the snapshots
		# share it.  Listing it with `lsinitrd` takes seconds, as every file
		# in it is printed
		if [ -z "${unpacked["$initrd"]:-}" ]; then
			dir="$(mktemp -d -p "$tmpdir")"
			(cd "$dir" && lsinitrd --unpack "$boot_root$initrd" \
				etc/crypttab \
				usr/lib/systemd/system-generators/measure-pcr-generator \
				usr/lib/systemd/system/measure-pcr-boundary.service) &> /dev/null || :
			[ -e "$dir/usr/lib/systemd/system/measure-pcr-boundary.service" ] || return 1
			# The line that orders the other devices after the anchor
			# shellcheck disable=SC2016  # literal
			grep -qsF 'After=systemd-cryptsetup@$anchor.service' \
				"$dir/usr/lib/systemd/system-generators/measure-pcr-generator" || return 1
			unpacked["$initrd"]="$dir"
		fi
		dir="${unpacked["$initrd"]}"
		# The crypttab of the addons, as they go after the initrd.  Without
		# one, the crypttab of the initrd
		crypttab="$(addons_crypttab "${files[@]:1}")"
		[ -n "$crypttab" ] || [ ! -e "$dir/etc/crypttab" ] || crypttab="$(< "$dir/etc/crypttab")"
		names=""
		[ -z "$crypttab" ] || names="$(crypttab_names <<<"$crypttab")"
		[ "$names" = "$expected" ] || return 1
		# The anchor measures, and no other device does.  With DPS the anchor
		# has no crypttab line: the partition discovery opens it and measures
		# it
		[ -n "$crypttab" ] || continue
		while read -r name _ _ opts; do
			[[ "$name" != \#* ]] || continue
			if [ "$name" = "$anchor" ]; then
				[[ "$opts" == *"tpm2-measure-pcr=yes"* ]] || return 1
			else
				[[ "$opts" != *"tpm2-measure-pcr=yes"* ]] || return 1
			fi
		done <<<"$crypttab"
	done < <(jq -r '.[] | select(.type == "type1") | '"$jq_initrd_files" < "$entryfile" | sort -u)
}

# The keyslots of the pcrlock TPM2 slots of "$1" that are not bound to
# PCR 15 and have no PIN
unbound_tpm2_keyslots()
{
	luks_header "${1:?}" | jq -r "$jq_tpm2_token_defs"'
		.tokens[] | select(pcrlock and (bound | not) and (pin | not)) | .keyslots[]'
}

# The TPM2 slots enrolled before the anchor existed carry only the
# pcrlock policy, so they also unseal once the system is up.  Next to
# each of them, add a slot bound to PCR 15, as `enroll_tpm2` does.  The
# old slot still unseals here, so it unlocks the device and no password
# is needed.  The old slot stays as the fallback.  A slot with a PIN is
# left alone, as the new slot would need the PIN too
rebind_tpm2_slots()
{
	[ -e /var/lib/systemd/pcrlock.json ] || return 0
	detect_tracked_devices || return 0

	local anchor dev value slot keyslots replaced=() public_key_args
	local -A bindings
	anchor="$(measure_anchor)" || return 0
	# Without the option, the device was enrolled with --no-measure-pcr
	[[ "$(crypttab_field "$anchor" options)" == *"tpm2-measure-pcr=yes"* ]] || return 0

	for dev in "${tracked_devices[@]}"; do
		# Older enrollments measure every device.  The values below expect
		# that only the anchor measures, so remove the option from the other
		# devices.  The next initrd uses this change
		[ "$dev" = "$anchor" ] || \
			[[ "$(crypttab_field "$dev" options)" != *"tpm2-measure-pcr=yes"* ]] || \
			remove_crypttab_option "$dev" 'tpm2-measure-pcr=yes'
		bindings["$dev"]="$(tpm2_slot_binding "$dev")"
		[ "${bindings["$dev"]}" = "plain" ] || continue
		# Read the crypttab of the initrd only when a slot needs it.  This is
		# because this function runs after every update of the predictions
		[ "$dev" = "$anchor" ] || read_initrd_crypttab
		! pcr15_unbound_device "$dev" "$anchor" || continue
		value="$(pcr15_slot_value "$dev" "$anchor")" || continue
		# The same kind of slot that `enroll_tpm2` makes
		uki_public_key_args public_key_args "$dev" "$anchor" || {
			warn "No public key for the signed PCR 11 policy of the UKIs, $dev keeps its TPM2 slot"
			continue
		}
		info "Binding a new TPM2 slot of $dev to the initrd"
		systemd-cryptenroll \
			--tpm2-device=auto \
			"${public_key_args[@]}" \
			--tpm2-pcrlock=/var/lib/systemd/pcrlock.json \
			--tpm2-pcrs="15:sha256=$value" \
			--unlock-tpm2-device=auto \
			"$dev" < /dev/null || { warn "Failed to bind a new TPM2 slot of $dev to the initrd"; continue; }
		bindings["$dev"]="bound+plain"
	done

	# The old slots are removed once nothing that boots needs them
	for dev in "${tracked_devices[@]}"; do
		[ "${bindings["$dev"]}" != "bound+plain" ] || replaced+=("$dev")
	done
	[ "${#replaced[@]}" -gt 0 ] || return 0
	entries_bind_pcr15 "$(crypttab_field "$anchor" name)" || return 0
	for dev in "${replaced[@]}"; do
		mapfile -t keyslots < <(unbound_tpm2_keyslots "$dev")
		for slot in "${keyslots[@]}"; do
			info "Removing the TPM2 slot $slot of $dev, that also unseals on the running system"
			systemd-cryptenroll --wipe-slot="$slot" --unlock-tpm2-device=auto "$dev" < /dev/null || \
				warn "Failed to remove the TPM2 slot $slot of $dev"
		done
	done
}

detect_tracked_devices()
{
	local dev fstype
	! have_tracked_devices || return 0

	dbg_cat "/etc/crypttab"

	while read -r dev fstype; do
		[ "$fstype" = 'crypto_LUKS' ] || continue
		cryptsetup isLuks --type luks2 "$dev" || continue
		is_tracked_device "$dev" || continue
		dbg "Tracking encrypted device $dev"
		tracked_devices+=("$dev")
	# --list prints every device once.  The default tree repeats a device
	# under each of its parents.  With it, a RAID would be tracked (and
	# enrolled) once per member disk
	done < <(lsblk --noheadings --list -o PATH,FSTYPE)
	have_tracked_devices
}

have_tpm2()
{
	[ -n "$(systemd-cryptenroll --tpm2-device=list 2> /dev/null)" ]
}

have_fido2()
{
	[ -n "$(systemd-cryptenroll --fido2-device=list 2> /dev/null)" ]
}

have_slot()
{
	local dev="${1:?}"
	local kind="${2:?}"
	grep -q "$kind" < <(systemd-cryptenroll "$dev")
}

luks_header()
{
	cryptsetup luksDump --dump-json-metadata "${1:?}"
}

# systemd-cryptenroll exits successfully even when it did not enroll
# anything.  A slot of the expected kind is not proof by itself, as it
# can come from a previous enrollment.  So the LUKS2 header is compared
# with the one collected before the enrollment.  TPM2 has one
# exception, see below
check_enrolled()
{
	local dev="${1:?}"
	local kind="${2:?}"
	local header="${3:?}"

	# Both cases are a failed enrollment, but they are different failures,
	# so they are reported apart.  The first one leaves the device exactly
	# as it was.  The second one does not.  The caller rolls back only
	# "/etc/crypttab" and the initrd, never the LUKS2 header.  So whatever
	# was written to the header stays
	if [ "$header" = "$(luks_header "$dev")" ]; then
		# The exception is TPM2.  systemd-cryptenroll does nothing when a slot
		# with the same policy hash is already there (unless a PIN is set).
		# With pcrlock that hash depends only on the NV index, so enrolling
		# again never changes the header.  The slot that is there is the one
		# that was asked for
		if [ "$kind" = "tpm2" ] && have_slot "$dev" "tpm2"; then
			dbg "The TPM2 policy of $dev is already enrolled"
			return 0
		fi
		warn "systemd-cryptenroll reported no error, but it left the header of $dev untouched: nothing was enrolled with $kind"
		return 1
	fi

	if ! have_slot "$dev" "$kind"; then
		warn "systemd-cryptenroll reported no error and did change the header of $dev, but there is no $kind slot in it. The change is something else, and it is still there"
		return 1
	fi
}

# Whether "$1" has a TPM2 slot of pcr-oracle: a signed PCR policy
# without pcrlock.  The slots of the UKIs have both
has_signed_pcr_policy()
{
	luks_header "${1:?}" 2> /dev/null | \
		jq -e "$jq_tpm2_token_defs"'any(.tokens[]?; .type == "systemd-tpm2" and signed and (pcrlock | not))' &> /dev/null
}

# Whether the slot of kind "$2" of "$1" can authorize a new slot with
# nobody in front of the machine.  A TPM2 slot with a PIN cannot.
# systemd-cryptenroll has to unseal it, and it reads the current PIN
# only from a terminal.  Its FIDO2 and password paths pass
# ASK_PASSWORD_ACCEPT_CACHED, but its TPM2 path does not.  So
# %user:tpm2-pin is never consulted.  The only other source is
# $CREDENTIALS_DIRECTORY/cryptenroll.tpm2-pin, and nothing sets it
# here.  A FIDO2 token cannot either when it asks for its PIN, for user
# verification, or just for a touch
#
# `have_slot` cannot tell these cases apart, as it only greps the list
# that systemd-cryptenroll prints.  The LUKS2 token does tell them
# apart
slot_is_unattended()
{
	local dev="${1:?}"
	local kind="${2:?}"
	local type interactive

	case "$kind" in
		tpm2)
			type="systemd-tpm2"
			interactive='."tpm2-pin" // false'
			;;
		fido2)
			type="systemd-fido2"
			interactive='[."fido2-clientPin-required", ."fido2-up-required", ."fido2-uv-required"] | any'
			;;
		*)
			return 1
			;;
	esac

	local header
	header="$(luks_header "$dev" 2> /dev/null)" || return 1

	jq -e --arg type "$type" 'any(.tokens[]?; .type == $type)' <<< "$header" &> /dev/null || return 1

	if jq -e --arg type "$type" "any(.tokens[]?; .type == \$type and ($interactive))" \
	      <<< "$header" &> /dev/null; then
		info "Not unlocking using ${kind^^}: the slot of $dev asks for a PIN or a touch"
		return 1
	fi
}

# Whether a slot of this kind can authorize a new slot right now.  With
# a terminal, somebody can answer the PIN prompt of systemd-cryptenroll
# or of the token itself, so any slot will do.  Without a terminal,
# only a slot that unseals on its own will do
can_unlock()
{
	local dev="${1:?}"
	local kind="${2:?}"

	# Some slots are bound to PCR 15 before the end of the initrd: the slot
	# of the anchor, and the slots of the devices of the initrd (see
	# `pcr15_slot_value`).  These slots never open on the running system
	if [ "$kind" = "tpm2" ] && [ "$(tpm2_slot_binding "$dev")" = "bound" ]; then
		local anchor
		anchor="$(measure_anchor)" || anchor=
		read_initrd_crypttab
		if [ "$(device_stage "$dev" "$anchor")" != late ]; then
			info "Not unlocking using TPM2: the slot of $dev opens only in the initrd"
			return 1
		fi
	fi

	if [ -t 0 ]; then
		have_slot "$dev" "$kind"
	else
		slot_is_unattended "$dev" "$kind"
	fi
}

in_lockout()
{
	command -v tpm2_getcap > /dev/null || { warn "tpm2_getcap not found"; return 1; }

	# `tpm2-tools` probes a fixed list of TCTIs, and `tabrmd` comes before
	# the device.  Some systems have `libtss2-tcti-tabrmd0` installed but
	# no `tpm2-abrmd` running.  There the library loads, fails to reach the
	# service on the bus, and prints a GDBus warning plus "Could not
	# initialize TCTI file".  Then it falls back to /dev/tpmrm0.  Nothing
	# is broken by that.  But it is the first thing on stderr, and an
	# installer that collects stderr reports it as the reason for whatever
	# fails next.  Naming the device skips the probe.
	#
	# Every `systemd-cryptenroll` and `systemd-pcrlock` call here already
	# talks to this same device.  `tpm2_context_new` hardcodes it, for the
	# same reason
	TPM2TOOLS_TCTI="device:/dev/tpmrm0" tpm2_getcap properties-variable | grep -q 'inLockout: *1'
}

# The path of the device "$1" of /etc/crypttab.  It resolves the four
# specifications that systemd-cryptsetup-generator resolves.
# crypttab(5) documents only "UUID=".  Like the generator, UUID and
# PARTUUID go through /dev/disk/by-*
device_path()
{
	local dev="$1"
	case "$dev" in
		UUID=*) dev="/dev/disk/by-uuid/${dev#UUID=}" ;;
		PARTUUID=*) dev="/dev/disk/by-partuuid/${dev#PARTUUID=}" ;;
		LABEL=*|PARTLABEL=*) dev="$(blkid --list-one --output device --match-token "$dev")" ;;
	esac
	echo "$dev"
}

# The device number of "$1" (see `device_path`), into the variable
# named "$2".  Empty when "$1" is not a block device.  The result is
# remembered for the run, as /etc/crypttab is matched against every
# tracked device
declare -gA device_numbers
device_number()
{
	local name="$1"
	local -n dn_number="${2:?}"
	local dev

	if [ -z "${device_numbers["$name"]+set}" ]; then
		dev="$(device_path "$name")"
		# A name that does not resolve into a block device is not the same
		# device as anything else.  Without this, any two such names would
		# match: with an empty device number, or with 0:0 for an image file
		# (crypttab also accepts those)
		device_numbers["$name"]=""
		[ ! -b "$dev" ] || device_numbers["$name"]="$(stat -L -c "%t:%T" "$dev")"
	fi
	# shellcheck disable=SC2034  # nameref
	dn_number="${device_numbers["$name"]}"
}

is_same_device()
{
	local id1 id2
	device_number "$1" id1
	device_number "$2" id2
	[ -n "$id1" ] && [ "$id1" = "$id2" ]
}

# /etc/crypttab belongs to whoever wrote it.  So only the line of the
# device being enrolled is ever rewritten.  The comments, the blank
# lines and the spacing of every other entry are copied back untouched.
# Both callers build the new file the same way and end here
#
# The file is installed only when a line really changed.  Replacing
# the file with an identical copy still moves the mtime.  On a
# transactional system, it also adds the file to the snapshot.  So a
# run with nothing to do would leave the same trace as a run that
# enrolled a device
replace_crypttab()
{
	local new="${1:?}"
	local changed="$2"

	[ -n "$changed" ] || {
		rm -f "$new"
		return 0
	}

	mv -Z "$new" /etc/crypttab
	chmod 644 /etc/crypttab
}

# Copy a line of /etc/crypttab that this run does not modify.  There is
# one exception: the header that sdbootutil used to write.  That header
# says that the comments will be removed, which is no longer true.  It
# is dropped, but dropping it alone is not a reason to rewrite the file
copy_crypttab_line()
{
	local line="$1"
	local new="$2"

	[[ "$line" != "# File created by sdbootutil."* ]] || return 0
	printf '%s\n' "$line" >> "$new"
}

add_crypttab_option()
{
	local dev="$1"
	local option="$2"

	dbg "Adding \"$option\" for \"$dev\" to /etc/crypttab"
	dbg_cat "/etc/crypttab"

	local crypttab
	crypttab="$(mktemp -t crypttab.XXXXXX)"

	local found=
	local changed=
	local line
	local name
	local device
	local key
	local opts
	# A file with no newline at the end still has a last entry
	while IFS= read -r line || [ -n "$line" ]; do
		read -r name device key opts <<<"$line"
		# Copy the line unchanged when it is a comment, a blank line, another
		# device, or a device that asked not to be tracked
		if [ -z "$name" ] || [[ "$name" = \#* ]] || \
		   ! is_same_device "$dev" "$device" || \
		   [[ "$opts" = *"x-sdbootutil.ignore"* ]]; then
			copy_crypttab_line "$line" "$crypttab"
			continue
		fi

		found=1
		if [[ "$opts" = *"$option"* ]]; then
			copy_crypttab_line "$line" "$crypttab"
			continue
		fi

		[ -z "$opts" ] && opts="$option" || opts="$opts,$option"
		# The key is written even when the entry did not have one.  With an
		# empty third field, the options would be read as the key
		echo "$name $device ${key:-none} $opts" >> "$crypttab"
		changed=1
		# crypttab changed, so the initrd needs to be rebuilt
		arg_no_reuse_initrd=1
	done < /etc/crypttab

	replace_crypttab "$crypttab" "$changed"

	# The enrollment alone does not make the device unlock at boot.  When
	# the option is not in /etc/crypttab (nor in the initrd that embeds
	# it), the boot can only ask for the password
	[ -n "$found" ] || \
		warn "$dev is not tracked by /etc/crypttab, so \"$option\" was not added"

	dbg "Added \"$option\" for \"$dev\" to /etc/crypttab"
	dbg_cat "/etc/crypttab"
}

remove_crypttab_option()
{
	local dev="$1"
	local option="$2"

	dbg "Removing \"$option\" for \"$dev\" to /etc/crypttab"
	dbg_cat "/etc/crypttab"

	local crypttab
	crypttab="$(mktemp -t crypttab.XXXXXX)"

	local changed=
	local line
	local name
	local device
	local key
	local opts
	while IFS= read -r line || [ -n "$line" ]; do
		read -r name device key opts <<<"$line"
		if [ -z "$name" ] || [[ "$name" = \#* ]] || \
		   ! is_same_device "$dev" "$device" || \
		   [[ "$opts" = *"x-sdbootutil.ignore"* ]] || \
		   [[ "$opts" != *"$option"* ]]; then
			copy_crypttab_line "$line" "$crypttab"
			continue
		fi

		opts="${opts#"$option",}"
		opts="${opts//,"$option"}"
		opts="${opts//"$option"}"
		echo "$name $device ${key:-none}${opts:+ $opts}" >> "$crypttab"
		changed=1
		# crypttab changed, so the initrd needs to be rebuilt
		arg_no_reuse_initrd=1
	done < /etc/crypttab

	replace_crypttab "$crypttab" "$changed"

	dbg "Removed \"$option\" for \"$dev\" to /etc/crypttab"
	dbg_cat "/etc/crypttab"
}

# systemd-cryptenroll needs to authorize the new slot with a credential
# that the device already accepts.  This is a password (read from
# %user:cryptenroll) or a token that can unlock the device.  With
# neither, it falls back to its own prompt.  When there is no terminal
# to answer it, the enrollment blocks forever
require_unlock()
{
	local dev="${1:?}"

	unlock_method=

	# A password that the device accepts comes first.  This is because a
	# TPM2 or a FIDO2 slot can be there and still not unlock.  The policy
	# can be stale after a firmware update (which is a reason to enroll
	# again), and the token can be unplugged.  The password itself is not
	# used here.  What matters is the side effect of `get_device_password`:
	# it leaves a valid password in %user:cryptenroll, where
	# systemd-cryptenroll looks for it
	get_device_password "$dev"
	[ -z "${device_pw:+set}" ] || return 0

	# Do not unlock with a TPM2 slot when enrolling TPM2
	if [ "$arg_method" != "tpm2" ] && [ "$arg_method" != "tpm2+pin" ] && can_unlock "$dev" "tpm2"; then
		info "Unlocking using TPM2"
		unlock_method="--unlock-tpm2-device=auto"
	# Same for FIDO2
	elif [ "$arg_method" != "fido2" ] && can_unlock "$dev" "fido2"; then
		info "Unlocking using FIDO2"
		unlock_method="--unlock-fido2-device=auto"
	fi

	# A terminal means that somebody can answer the prompt of
	# systemd-cryptenroll
	if [ -z "$unlock_method" ] && [ ! -t 0 ]; then
		warn "No valid password found for $dev, and there is no terminal to ask for one"
		warn "Provide it in the %user:cryptenroll kernel keyring entry"
		return 1
	fi

	return 0
}

# Make sure that systemd-cryptenroll can authorize a new slot of "$1".
# It uses the password in %user:cryptenroll, or a token.  The token
# option is added to the "extra_args" of the caller
enroll_unlock_args()
{
	require_unlock "$1" || return 1
	[ -z "$unlock_method" ] || extra_args+=("$unlock_method")
}

# The TPM2 PIN is in the variable named $2.  It is empty for "tpm2"
enroll_tpm2()
{
	local dev="$1"
	local pin_name="$2"
	local extra_args=()

	if [ -z "${!pin_name:+set}" ]; then
		info "Enrolling with TPM2: $dev"
	else
		info "Enrolling with TPM2+PIN: $dev"
		extra_args+=(--tpm2-with-pin=1)
	fi

	if [ ! -f /var/lib/systemd/pcrlock.json ]; then
		warn "Could not find /var/lib/systemd/pcrlock.json"
	fi

	enroll_unlock_args "$dev" || return 1

	local pcr_oracle_key public_key_args late=
	! pcr15_unbound_device "$dev" "$enroll_anchor" || late=1
	uki_public_key_args public_key_args "$dev" "$enroll_anchor" || \
		err "No public key for the signed PCR 11 policy of the UKIs"
	[ "${public_key_args[0]}" != "--tpm2-public-key=" ] || ! pcr_oracle_key="$(pcr_oracle_public_key)" || \
		warn "Ignoring $pcr_oracle_key for the enrollment. Remove it, and the private key, if pcr-oracle is not used anymore"

	local value
	if [ -n "$enroll_anchor" ] && [ -n "$late" ]; then
		info "The TPM2 slot of $dev is not bound to PCR 15: with the UKIs it opens after the initrd"
	elif [ -n "$enroll_anchor" ]; then
		if value="$(pcr15_slot_value "$dev" "$enroll_anchor")"; then
			extra_args+=("--tpm2-pcrs=15:sha256=$value")
		else
			info "The TPM2 slot of $dev is not bound to the initrd yet: the anchor $enroll_anchor was not measured in this boot"
		fi
	fi

	local header
	header="$(luks_header "$dev")"

	# Only PCR 15, when bound, is stored in the LUKS2 header.  The other
	# PCRs are in the pcrlock policy
	run_with_secret NEWPIN "$pin_name" systemd-cryptenroll \
	       --wipe-slot=tpm2 \
	       --tpm2-device=auto \
	       "${public_key_args[@]}" \
	       "${extra_args[@]}" \
	       --tpm2-pcrlock=/var/lib/systemd/pcrlock.json \
	       "$dev" || return 1
	check_enrolled "$dev" "tpm2" "$header" || return 1

	# Some PCR predictions do not match the current system state, so they
	# are left out of the policy.  Enable an update on the next boot, which
	# should include them
	systemctl --quiet enable sdbootutil-update-predictions.service || true
}

enroll_fido2()
{
	local dev="$1"

	info "Enrolling with FIDO2: $dev"

	local extra_args=()
	enroll_unlock_args "$dev" || return 1

	local header
	header="$(luks_header "$dev")"

	systemd-cryptenroll --wipe-slot=fido2 --fido2-device=auto "${extra_args[@]}" "$dev" || return 1
	check_enrolled "$dev" "fido2" "$header" || return 1
}

# The new password is in the variable named $2
enroll_password()
{
	local dev="$1"
	local pw_name="$2"

	info "Enrolling with password: $dev"

	local extra_args=()
	enroll_unlock_args "$dev" || return 1

	local header
	header="$(luks_header "$dev")"

	run_with_secret NEWPASSWORD "$pw_name" systemd-cryptenroll --wipe-slot=password --password "${extra_args[@]}" "$dev" || return 1
	check_enrolled "$dev" "password" "$header" || return 1
}

enroll_recovery_key()
{
	local dev="$1"

	info "Enrolling with recovery key: $dev"

	local extra_args=()
	enroll_unlock_args "$dev" || return 1

	# From here on the recovery key is handled.  See "Secrets and
	# --start-trace-code"
	local -; set +x

	# If no recovery key is provided, systemd-cryptenroll generates one
	local key keyid keyid_key keyid_int keyid_dep
	keyid_key="$(keyctl id %user:sdbootutil-key 2> /dev/null)" || true
	keyid_int="$(recovery_pin_keyid)" || true
	keyid_dep="$(keyctl id %user:sdbootutil 2> /dev/null)" || true
	if [ -n "$arg_ask_key" ]; then
		ask_new_password "recovery key" key
	elif [ -n "$env_key" ]; then
		key="$env_key"
	elif [ -n "$keyid_key" ]; then
		key="$(keyctl pipe "$keyid_key")"
	elif [ -n "$env_recovery_pin" ]; then
		# There is no recovery key, but there is a recovery PIN.  Make both the
		# same (see below).  RECOVERY_PIN wins over the keyring entry, as it
		# does in `generate_tpm2_predictions_pcrlock`
		key="$env_recovery_pin"
	elif [ -n "$keyid_int" ]; then
		key="$(keyctl pipe "$keyid_int")"
	elif [ -n "$keyid_dep" ]; then
		deprecated_keyring_secret "recovery key" "sdbootutil-key"
		key="$(keyctl pipe "$keyid_dep")"
	fi

	local header
	header="$(luks_header "$dev")"

	local generated_key='' old_slots=''
	# This function is called for every device.  Let systemd generate a
	# secure recovery key only the first time, and only when no recovery
	# key or PIN is selected (%user:sdbootutil-key,
	# %user:sdbootutil-recovery-pin)
	if [ -z "$key" ]; then
		# systemd-cryptenroll prints the recovery key on stdout, and the rest
		# of the information on stderr
		key="$(systemd-cryptenroll --wipe-slot=recovery --recovery-key "${extra_args[@]}" "$dev" 2> /dev/null)" || return 1
		generated_key=1
	else
		# A recovery key was already chosen, so use it for all the devices.
		# systemd-cryptenroll always generates a random recovery key, but we
		# want $key.  So cryptsetup replaces the random key with $key.  This
		# way systemd-cryptenroll can still use %u:cryptenroll, and cryptsetup
		# uses the temporary recovery key.  Neither asks for a password
		#
		# The old recovery keys are removed only once the new one opens the
		# device, so a failure keeps them
		local tmp_key slot type keyslot=
		while read -r slot type; do
			[ "$type" = "recovery" ] || continue
			old_slots+="${old_slots:+,}$slot"
		done < <(systemd-cryptenroll "$dev")
		tmp_key="$(systemd-cryptenroll --recovery-key "${extra_args[@]}" "$dev" 2> /dev/null)" || return 1
		while read -r slot type; do
			[ "$type" = "recovery" ] && [[ ",$old_slots," != *",$slot,"* ]] && keyslot="$slot"
		done < <(systemd-cryptenroll "$dev")
		[ -n "$keyslot" ] || return 1
		# cryptsetup reads the new passphrase from a key file.  Here that is a
		# pipe, never a file on disk
		cryptsetup luksChangeKey --key-slot "$keyslot" --force-password "$dev" <(echo -n "$key") <<<"$tmp_key" || {
			systemd-cryptenroll --wipe-slot="$keyslot" "${extra_args[@]}" "$dev" &> /dev/null
			return 1
		}
	fi

	check_enrolled "$dev" "recovery" "$header" || return 1
	# The key is published below, so it has to open the device
	valid_password "$dev" key || {
		warn "The recovery key does not open $dev"
		return 1
	}
	[ -z "$old_slots" ] || systemd-cryptenroll --wipe-slot="$old_slots" "${extra_args[@]}" "$dev" &> /dev/null || {
		warn "Cannot remove the old recovery keys of $dev"
		return 1
	}

	if [ -n "$generated_key" ]; then
		echo "Recovery key: $key"
		if command -v qrencode > /dev/null; then
			echo "You can also scan it with your mobile phone:"
			echo -n "$key" | qrencode -t utf8i
		fi
	fi

	# Make sure that the enrolled recovery key is in the kernel keyring, so
	# that systemd-cryptenroll can use it
	keyid="$(keyctl id %user:cryptenroll 2> /dev/null)" || true
	if [ -z "$keyid" ] && [ -z "$unlock_method" ]; then
		keyctl_add_with_timeout "cryptenroll" key
	fi
	# ... and give it to --method=tpm2[+pin] via a private keyring.  This
	# way the key enrolled here is also the recovery PIN that seals the
	# pcrlock NVIndex, and the user has a single secret to keep.  This is
	# only possible while the NVIndex has no PIN yet, or while its PIN is
	# reachable.  The PIN cannot be read back from the TPM2.
	# `systemd-pcrlock` takes a single --recovery-pin, which has to
	# authorize the old NVIndex and seal the new one.  So this key cannot
	# replace the PIN either.  All the devices share one NVIndex
	local reachable_pin='' sealed='' rdev
	[ ! -e /var/lib/systemd/pcrlock.json ] || sealed=1
	for rdev in "$dev" "${tracked_devices[@]}"; do
		! have_slot "$rdev" tpm2 || sealed=1
	done
	if [ -n "$env_recovery_pin" ]; then
		reachable_pin="$env_recovery_pin"
	elif [ -n "$keyid_int" ]; then
		reachable_pin="$(keyctl pipe "$keyid_int")"
	fi
	if [ -n "$reachable_pin" ]; then
		# The value shown is the recovery PIN, and it is not replaced.  That
		# PIN cannot be recovered from anywhere else
		[ "$key" = "$reachable_pin" ] || \
			warn "The recovery key and the recovery PIN are now different"
	elif [ -n "$sealed" ]; then
		# A PIN sealed the NVIndex of this enrollment, and it is not reachable
		# here, so this key is not that PIN.  Publishing the key would name as
		# the recovery PIN a value that no policy update can use.  Then
		# `status` and `warn_no_recovery_pin` would report a PIN that is not
		# there.  That warning is the one that must reach a machine heading
		# into the dead end of github issue 250
		warn "There is already a recovery PIN for the TPM2, and it is not reachable here"
		warn "The recovery key and the recovery PIN are now different"
	else
		keyctl_add_with_timeout "sdbootutil-recovery-pin" key
	fi
}

# The PIN or the password, if the method takes one, is in the variable
# named $2
enroll_device()
{
	local dev="$1"
	local secret_name="$2"

	case "$arg_method" in
		"tpm2"|"tpm2+pin")
			enroll_tpm2 "$dev" "$secret_name"
			;;

		"fido2")
			enroll_fido2 "$dev"
			;;

		"password")
			enroll_password "$dev" "$secret_name"
			;;

		"recovery-key")
			enroll_recovery_key "$dev"
			;;

		*)
			local msg
			if [ -n "$arg_method" ]; then
				msg="Unexpected parameter for --method=: $arg_method"
			else
				msg="Missing value for parameter --method="
			fi
			err "$msg\nValid methods: tpm2,tpm2+pin,fido2,password,recovery-key"
			;;
	esac
}

# Get the PIN (tpm2+pin) or the password (password).  The sources are
# the %u keyring entry "sdbootutil-tpm2-pin" / "sdbootutil-pw", the PIN
# or PW environment variable, or a prompt to the user.  Like --ask-key
# in `enroll_recovery_key`, an explicit --ask-pin or --ask-pw wins over
# the other sources.  The secret goes to the variable named $1,
# untraced
# shellcheck disable=SC2034  # the namerefs are written for the caller
enroll_secret()
{
	local -; set +x
	local es_name="$1"
	local -n es_secret="$1"
	local label env ask keyring keyid keyid_dep
	case "$arg_method" in
		tpm2+pin) label="TPM2 PIN" env="$env_pin" ask="$arg_ask_pin" keyring=sdbootutil-tpm2-pin ;;
		password) label="password" env="$env_pw" ask="$arg_ask_pw" keyring=sdbootutil-pw ;;
		*) return 0 ;;
	esac
	keyid="$(keyctl id %user:"$keyring" 2> /dev/null)" || true
	keyid_dep="$(keyctl id %user:sdbootutil 2> /dev/null)" || true
	if [ -n "$ask" ]; then
		ask_new_password "$label" "$es_name"
	elif [ -n "$env" ]; then
		es_secret="$env"
	elif [ -n "$keyid" ]; then
		es_secret="$(keyctl pipe "$keyid")"
	elif [ -n "$keyid_dep" ]; then
		deprecated_keyring_secret "$label" "$keyring"
		es_secret="$(keyctl pipe "$keyid_dep")"
	else
		ask_new_password "$label" "$es_name"
	fi
}

# The device that measures its volume key, for `enroll_tpm2`.  `enroll`
# sets it.  It is empty with --no-measure-pcr, or without an encrypted
# root
enroll_anchor=
enroll()
{
	[ -e /etc/crypttab ] || { info "/etc/crypttab not found. No encrypted devices?"; return 0; }
	command -v systemd-cryptenroll > /dev/null || { info "systemd-cryptenroll not found"; return 0; }
	detect_tracked_devices || { info "No LUKS2 devices found"; return 0; }

	info "Enrolling devices ($arg_method): ${tracked_devices[*]}"

	# From here on, /etc/crypttab can ask for a method that no keyslot
	# backs yet.  If anything below fails, the trap puts the file back
	cp -p /etc/crypttab "$tmpdir/crypttab"
	restore_crypttab=1

	# Prepare /etc/crypttab and update initrd if required
	case "$arg_method" in
		"tpm2"|"tpm2+pin")
			have_tpm2 || err "No TPM2 found"
			have_pcrlock || err "No systemd-pcrlock found"
			! in_lockout || err "The TPM2 is in lockout. Use 'tpm2_dictionarylockout -c [ -p passwd ]' to continue"
			# Only the anchor measures its volume key, see
			# `measure_anchor`
			[ -n "$arg_no_measure_pcr" ] || enroll_anchor="$(measure_anchor)" || enroll_anchor=
			for dev in "${tracked_devices[@]}"; do
				add_crypttab_option "$dev" 'tpm2-device=auto'
				[ -n "$enroll_anchor" ] || continue
				if [ "$dev" = "$enroll_anchor" ]; then
					add_crypttab_option "$dev" 'tpm2-measure-pcr=yes'
				else
					remove_crypttab_option "$dev" 'tpm2-measure-pcr=yes'
				fi
			done
			;;

		"fido2")
			have_fido2 || err "No FIDO2 key found"
			for dev in "${tracked_devices[@]}"; do
				add_crypttab_option "$dev" 'fido2-device=auto'
			done
			;;
	esac

	# The new TPM2 slots are made for the UKI mode of the configuration.
	# So from here on that mode is in effect, and the entries are written
	# again when the mode changes.  The key of the signed PCR 11 policy of
	# UKI="local" needs "tpm2-device" in /etc/crypttab, added above
	local tpm2="" mode_changed=""
	case "$arg_method" in
		tpm2|tpm2+pin) tpm2=1 ;;
	esac
	if [ -n "$tpm2" ]; then
		if [ "${UKI:-}" != "$uki_config" ]; then
			mode_changed=1
			restore_uki=1
		fi
		UKI="$uki_config"
		uki_keys
	fi

	# If /etc/crypttab changed (this is expected), a new initrd is needed.
	# With the UKIs, the entries are always checked.  This is because the
	# first TPM2 enrollment makes the key of the signed PCR 11 policy, and
	# the UKIs must carry it
	if [ "$arg_no_reuse_initrd" = "1" ] || [ -n "$mode_changed" ] || { [ -n "$tpm2" ] && uki_selected; }; then
		install_all_kernels "$root_snapshot"
	fi

	if [ -n "$tpm2" ]; then
		# Which devices the initrd unlocks, see `enroll_tpm2`.  Read it from
		# the entries written above, as a distribution UKI can unlock other
		# devices
		initrd_crypttab_read=
		if [ -n "$enroll_anchor" ] || uki_selected; then
			read_initrd_crypttab
		fi

		# During the initial enrollment, systemd-pcrlock is expected to get
		# the recovery PIN from the %u keyring entry "sdbootutil[-pin]"
		#
		# This is done even when /etc/crypttab did not change.  This is
		# because the enrollment points to an NV index that can be missing
		# (for example after a `tpm2_clear`), or to a policy that does not
		# match the current system
		generate_tpm2_predictions
		# Do not call `generate_tpm2_predictions` again at the end of the
		# script
		update_predictions=
	fi

	# shellcheck disable=SC2034  # passed by name, see "Secrets and --start-trace-code"
	local pin_or_pw=
	enroll_secret pin_or_pw

	local failed=
	for dev in "${tracked_devices[@]}"; do
		enroll_device "$dev" pin_or_pw || { failed="$dev"; break; }
		# A slot is in place, so the options in /etc/crypttab are backed and
		# must stay, even if a later device fails.  Without "tpm2-device", the
		# policy of this slot would never be updated.  These options do no
		# harm to a device left without a slot: it asks for the password as
		# before.  The same goes for the UKI mode
		restore_crypttab=
		restore_uki=
	done

	# The trap puts /etc/crypttab back if no device was enrolled
	[ -z "$failed" ] || err "Failed to enroll ($arg_method): $failed"
}

unenroll_all_pcrlock()
{
	systemctl --quiet disable sdbootutil-update-predictions.service || true
	pcrlock remove-policy &> /dev/null || true
	rm -fr /var/lib/pcrlock.d/* || true
	rm -f /var/lib/systemd/pcrlock.json
	rm -f "${esp_root}${esp_dst}/pcrlock.json"
	rm -f /var/lib/sdbootutil/pcrlock-hashes
	rm -f /var/lib/sdbootutil/crypttab.sha1
	# The next enrollment records the ESP as it is then
	rm -f "$esp_files"
	rm -f /var/lib/sdbootutil/measure-pcr-private.pem
	rm -f /var/lib/sdbootutil/measure-pcr-public.pem
	rm -f /var/lib/sdbootutil/measure-pcr-prediction
	rm -f /var/lib/sdbootutil/measure-pcr-prediction.sha256
	rm -f "${esp_root}${esp_dst}/measure-pcr-prediction"
	rm -f "${esp_root}${esp_dst}/measure-pcr-prediction.sha256"
}

unenroll_all_pcr_oracle()
{
	rm -f /etc/systemd/tpm2-pcr-private-key.pem
	rm -f /etc/systemd/tpm2-pcr-public-key.pem
	rm -f /etc/systemd/tpm2-pcr-signature.json
	rm -f "${esp_root}${esp_dst}/tpm2-pcr-public-key.pem"
	rm -f "${esp_root}${esp_dst}/tpm2-pcr-signature.json"
	rm -f /var/lib/sdbootutil/measure-pcr-prediction
	rm -f /var/lib/sdbootutil/measure-pcr-prediction.sha256
	rm -f "${esp_root}${esp_dst}/measure-pcr-prediction"
	rm -f "${esp_root}${esp_dst}/measure-pcr-prediction.sha256"
}

unenroll_device()
{
	local dev="$1"

	local kind
	case "$arg_method" in
		"tpm2"|"tpm2+pin") kind=tpm2 ;;
		"fido2"|"password") kind="$arg_method" ;;
		"recovery-key")
			kind=recovery
			# When sdbootutil enrolled both, the recovery key and the recovery PIN
			# of the pcrlock NVIndex are the same secret.  Only the recovery key
			# lives in this slot.  The PIN stays in the TPM2, and it authorizes
			# the policy again on the next update.  So the value cannot be
			# discarded with the slot
			if have_slot "$dev" "tpm2"; then
				warn "The recovery PIN of the TPM2 policy is not removed with the recovery key of $dev"
				warn "Keep the value: it is still needed to update the predictions"
			fi
			;;

		*)
			local msg
			if [ -n "$arg_method" ]; then
				msg="Unexpected parameter for --method=: $arg_method"
			else
				msg="Missing value for parameter --method="
			fi

			local methods=()
			local line
			while read -r line; do
				[[ "$line" =~ [[:digit:]]+[[:space:]] ]] || continue
				IFS=" " read -r -a s <<<"$line"
				methods+=("${s[1]}")
			done < <(systemd-cryptenroll "$dev")
			[ "${#methods[@]}" -gt 0 ] || err "$msg\nThe device $dev has no enrollment"
			err "$msg\nMethods present in $dev: $(IFS=','; echo "${methods[*]}")"
			;;
	esac
	systemd-cryptenroll --wipe-slot="$kind" "$dev"
}

unenroll()
{
	[ -e /etc/crypttab ] || { info "/etc/crypttab not found. No encrypted devices?"; return 0; }
	command -v systemd-cryptenroll > /dev/null || { info "systemd-cryptenroll not found"; return 0; }
	detect_tracked_devices || { info "No LUKS2 devices found"; return 0; }

	info "Unenrolling devices ($arg_method): ${tracked_devices[*]}"

	# Prepare /etc/crypttab and update initrd if required
	case "$arg_method" in
		"tpm2"|"tpm2+pin")
			have_tpm2 || err "No TPM2 found"
			for dev in "${tracked_devices[@]}"; do
				remove_crypttab_option "$dev" 'tpm2-device=auto'
				remove_crypttab_option "$dev" 'tpm2-measure-pcr=yes'
			done
			;;

		"fido2")
			have_fido2 || err "No FIDO2 key found"
			for dev in "${tracked_devices[@]}"; do
				remove_crypttab_option "$dev" 'fido2-device=auto'
			done
			;;
	esac
	if [ "$arg_no_reuse_initrd" = "1" ]; then
		install_all_kernels "$root_snapshot"
		# Do not call `generate_tpm2_predictions` again at the end of the
		# script
		update_predictions=
	fi

	for dev in "${tracked_devices[@]}"; do
		unenroll_device "$dev"
	done

	# An unenroll can be partial.  So drop the policy and the assets only
	# when no device is left with a "tpm2" slot.  All the devices share the
	# same NVIndex
	if [ "$arg_method" = "tpm2" ] || [ "$arg_method" = "tpm2+pin" ]; then
		local unenroll_all=1
		# Reset the detected devices
		tracked_devices=()
		detect_tracked_devices
		for dev in "${tracked_devices[@]}"; do
			if have_slot "$dev" "tpm2"; then
				unenroll_all=0
				break
			fi
		done
		if [ "$unenroll_all" = 1 ]; then
			unenroll_all_pcrlock
			unenroll_all_pcr_oracle
		fi
	fi
}

# Every full disk encryption report starts with the same two questions.
# How is this machine encrypted?  Will the TPM2 open it on the next
# boot?  Answering them by hand means reading `cryptsetup luksDump`,
# /etc/crypttab, /var/lib/systemd/pcrlock.json, /var/lib/pcrlock.d, the
# LUKS2 tokens and the journal.  It also means knowing how they relate.
# That is the first exchange of every issue, and half of the issues are
# closed without the answer ever arriving
#
# Everything here only reads, so it is safe to ask a reporter to run
# it.  No policy is created, no keyring entry is written, the NVIndex
# is not touched and no file changes.  It also has to say something
# useful on a machine whose TPM2 is unusable, whose policy is missing,
# or that is not enrolled at all.  This is why so much of it reads
# "unknown"
#
# No secret is ever printed, only whether it exists.  The recovery PIN,
# the recovery key and the volume key are named, never shown
#
# Each section prints as it is probed.  jq is used only to parse what
# other tools produce: the LUKS2 header, `bootctl list`, the pcrlock
# policy and the measurement log.  This way a probe that dies half way
# costs one section, not the whole report

# The label is padded so that every value in the report starts at the
# same column.  This makes a wrong value easy to find.  Device rows are
# indented one level more and padded two characters less, so their
# values still line up with the rest
status_row()
{
	printf '  %-17s%s\n' "${1}:" "$2"
}

status_subrow()
{
	printf '    %-15s%s\n' "${1}:" "$2"
}

# "a, b, c", empty for no arguments
status_join()
{
	local out="" i

	for i in "$@"; do
		[ -n "$out" ] && out="$out, $i" || out="$i"
	done
	echo "$out"
}

# The state that the trailing warnings need.  It is the only thing
# that passes from one section to another.  Each variable is set while
# its section prints
status_policy_backend=
status_policy_stale=
status_tpm2_device=
status_pin_reachable=
status_dangling=

# Whether "$status_dangling" holds this entry.  The names in
# "$status_dangling" end with ".conf".  The boot loader interface
# variables leave out the ".conf", so both spellings are tried.  This is
# the same workaround as in `status_boot`
status_is_dangling()
{
	local id="$1"

	[ -n "$id" ] || return 1
	[ -n "$status_dangling" ] || return 1
	cut -d'|' -f1 <<<"$status_dangling" | grep -qxF -e "$id" -e "$id.conf"
}

crypttab_field()
{
	# Print a field of the crypttab line that describes this device, if
	# there is one.  `is_same_device` finds the line.  `is_tracked_device`
	# and `add_crypttab_option` find it the same way
	local dev="${1:?}"
	local field="${2:?}"
	local name device key opts

	[ -e /etc/crypttab ] || return 0

	while read -r name device key opts; do
		[[ "$name" != \#* ]] || continue
		[ -n "$name" ] || continue
		is_same_device "$dev" "$device" || continue
		case "$field" in
			name) echo "$name" ;;
			options) echo "$opts" ;;
		esac
		return 0
	done < /etc/crypttab
}

status_device()
{
	local dev="${1:?}" anchor="${2:-}"
	local header name opts

	# A header that cannot be read does not stop the report.  It explains
	# why the device does not open, so the report shows it
	header="$(luks_header "$dev" 2> /dev/null)" || header=""
	name="$(crypttab_field "$dev" name)"
	opts="$(crypttab_field "$dev" options)"

	local tracked=1 ignored=
	is_tracked_device "$dev" 2> /dev/null || tracked=
	[[ "$opts" != *"x-sdbootutil.ignore"* ]] || ignored=1

	# The keyslots come from the LUKS2 JSON.  They do not come from the
	# "SLOT TYPE" column of `systemd-cryptenroll`, because that column calls
	# "other" every type that it does not know.  A slot that no token points
	# at is a plain password.  The password is the only thing that still
	# opens the device when the TPM2 refuses.  So this fact must be right
	#
	# A "tpm2_pubkey" in the token means that a shard of the sealed key is
	# locked to a signed PCR policy.  Then unlocking also needs a
	# tpm2-pcr-signature.json.  "tpm2_pcrlock" means the NVIndex policy
	# instead.  These are two different backends.  Each one needs a
	# different place to look next
	local slots=""
	[ -z "$header" ] || slots="$(jq -r "$jq_tpm2_token_defs"'
		(.tokens // {}) as $tokens |
		(.keyslots // {}) | keys[] | . as $slot |
		($tokens | to_entries
		         | map(select(.value.keyslots // [] | index($slot)))
		         | first) as $token |
		[ $slot,
		  (if $token == null then "password"
		   elif $token.value.type == "systemd-tpm2" then
			(if ($token.value."tpm2-pin" // false) then "tpm2+pin" else "tpm2" end)
		   elif $token.value.type == "systemd-fido2" then "fido2"
		   elif $token.value.type == "systemd-recovery" then "recovery-key"
		   else $token.value.type end),
		  ($token.value.type // ""),
		  (if $token == null then ""
		   elif ($token.value | pcrlock) then
			", pcrlock NVIndex" + (if ($token.value | bound) then ", bound to PCR 15" else "" end)
				+ (if ($token.value | signed) then ", signed PCR 11" else "" end)
		   elif ($token.value | signed) then ", signed policy"
		   else "" end)
		] | @tsv' <<<"$header")"

	local slot method token extra methods=()
	while IFS=$'\t' read -r slot method token extra; do
		[ -n "$slot" ] || continue
		methods+=("$method")
	done <<<"$slots"

	# Sorted and without repeats, so that the same machine always gives
	# the same output
	local unique=()
	[ "${#methods[@]}" -eq 0 ] || \
		mapfile -t unique < <(printf '%s\n' "${methods[@]}" | sort -u)

	# A device that only the TPM2 can open becomes unopenable after one
	# firmware update.  The report warns about it
	local tpm2_only="" m
	if [ "${#unique[@]}" -gt 0 ]; then
		tpm2_only=1
		for m in "${unique[@]}"; do
			[[ "$m" == tpm2* ]] || tpm2_only=
			[[ "$m" != tpm2* ]] || status_tpm2_device=1
		done
	fi

	# A device that is not in /etc/crypttab is only listed with
	# --full.  The caller counts it
	[ -n "$arg_full" ] || [ -n "$tracked" ] || [ -n "$ignored" ] || return 1

	# A slot bound to PCR 15 only unseals in the initrd.  Some devices are
	# not unlocked by the initrd.  Their slots unseal after the initrd, so
	# they also unseal on the running system (see `pcr15_slot_value`)
	local binding=none where="" bound="opens it only in the initrd"
	[ -z "$header" ] || binding="$(tpm2_slot_binding "$dev" "$header")"
	# The anchor is opened in the initrd.  Only the other devices need
	# the crypttab of the initrd
	if [[ "$binding" == bound* ]] && [[ "$opts" != *"tpm2-measure-pcr=yes"* ]]; then
		read_initrd_crypttab
		[ "$(device_stage "$dev" "$anchor")" != late ] || bound="opens it after the initrd, also on the running system"
	fi
	# See `pcr15_unbound_device`
	if [ "$binding" = "plain" ] && uki_selected && [ -n "$anchor" ]; then
		read_initrd_crypttab
		! pcr15_unbound_device "$dev" "$anchor" || binding=late
	fi
	case "$binding" in
		late) where="opens it after the initrd, also on the running system (a late device with the UKIs)" ;;
		bound) where="$bound" ;;
		bound+plain) where="$bound, but an older slot still opens it on the running system" ;;
		plain|pin) where="opens it ALSO on the running system" ;;
	esac

	local methods_text="nothing"
	[ "${#unique[@]}" -eq 0 ] || methods_text="$(status_join "${unique[@]}")"

	local label="${dev}${name:+ ($name)}"
	if [ -n "$arg_full" ]; then
		echo "  $label"
		if [ -n "$ignored" ]; then
			status_subrow "Tracked" "no (x-sdbootutil.ignore)"
		elif [ -n "$tracked" ]; then
			status_subrow "Tracked" "yes"
		else
			status_subrow "Tracked" "no (not in /etc/crypttab)"
		fi
		[ -n "$header" ] || status_subrow "LUKS2 header" "CANNOT BE READ"
		status_subrow "Unlocks with" "$methods_text"
		if [[ "$opts" == *"tpm2-measure-pcr=yes"* ]]; then
			status_subrow "PCR 15" "measured (the anchor)"
		else
			status_subrow "PCR 15" "not measured"
		fi
		[ -z "$where" ] || status_subrow "TPM2 slot" "$where"
		while IFS=$'\t' read -r slot method token extra; do
			[ -n "$slot" ] || continue
			echo "    slot ${slot}: ${method}${token:+ ($token)}${extra}"
		done <<<"$slots"
	else
		local line="$methods_text"
		[ -n "$header" ] || line="LUKS2 header CANNOT BE READ"
		[ -z "$ignored" ] || line+="; ignored (x-sdbootutil.ignore)"
		[ -z "$where" ] || line+="; the TPM2 $where"
		echo "  $label: $line"
	fi

	case "$binding" in
		plain) status_warning "$label: the TPM2 slot also opens it on the running system.  The next 'sdbootutil update-predictions' adds a slot bound to the boot, once the anchor was measured" ;;
		pin) status_warning "$label: the TPM2 slot also opens it on the running system.  Enroll the TPM2 again ('sdbootutil enroll --method=tpm2+pin') to bind it to the boot" ;;
	esac

	[ -z "$tpm2_only" ] || \
		status_warning "$label: only the TPM2 can open it.  A firmware update, a bootloader update or a cleared TPM2 leaves it unopenable"

	# See `warn_tpm2_slot_without_option`
	[[ "$slots" != *", pcrlock NVIndex"* ]] || [ -z "$tracked" ] || [ -n "$ignored" ] || [[ "$opts" == *"tpm2-device"* ]] || \
		status_warning "$label: there is a TPM2 slot, but no \"tpm2-device\" option in /etc/crypttab, so the TPM2 policy is never updated"
	return 0
}

status_devices()
{
	local dev fstype all=()

	detect_tracked_devices > /dev/null 2>&1 || :

	# All the LUKS2 devices are listed, not only the tracked ones.  Some
	# devices are missing from /etc/crypttab, or carry "x-sdbootutil.ignore".
	# Such a device can explain a boot that asks for an unexpected password.
	# So it is listed and marked
	while read -r dev fstype; do
		[ "$fstype" = 'crypto_LUKS' ] || continue
		cryptsetup isLuks --type luks2 "$dev" 2> /dev/null || continue
		all+=("$dev")
	done < <(lsblk --noheadings --list -o PATH,FSTYPE)

	echo "Devices"
	if [ "${#all[@]}" -eq 0 ]; then
		echo "  none"
		return 0
	fi

	# The anchor is the same for every device, so it is read once
	local anchor others=0
	anchor="$(measure_anchor 2> /dev/null)" || anchor=
	for dev in "${all[@]}"; do
		status_device "$dev" "$anchor" || others=$((others + 1))
	done
	[ "$others" -eq 0 ] || \
		echo "  $others other LUKS2 device(s) not in /etc/crypttab ('status --full' lists them)"
}

status_policy()
{
	local policy=/var/lib/systemd/pcrlock.json
	local esp_policy="${esp_root}${esp_dst}/pcrlock.json"

	if [ -e "$policy" ]; then
		status_policy_backend="pcrlock"
	elif is_pcr_oracle; then
		status_policy_backend="pcr-oracle"
	fi

	[ -n "$status_policy_backend" ] || {
		status_row "Policy" "none, the TPM2 opens no device"
		return 0
	}

	# The two copies must be identical.  `dracut-pcr-signature` imports
	# the copy in the ESP.  The local copy stores the sealed PIN that
	# `systemd-pcrlock` needs to replace the NVIndex.  A machine with only
	# one of them still boots, but the *next* update fails
	local esp_state="missing"
	if [ -e "$esp_policy" ]; then
		if [ ! -e "$policy" ]; then
			esp_state="only-in-esp"
		elif cmp -s "$policy" "$esp_policy"; then
			esp_state="same"
		else
			esp_state="different"
		fi
	fi

	# `is_pcr_oracle` is also a backend, and it leaves no pcrlock.json.
	# Then everything read from that file is unknown.  Unknown is not the
	# same as absent
	local have_policy="" bank="sha256"
	if [ -e "$policy" ]; then
		have_policy=1
		bank="$(jq -r '.pcrBank // "sha256"' < "$policy")"
	fi

	# The list is rebuilt, not printed as it is.  So a list with an empty
	# or a repeated field looks like the rest of the report
	local requested="" i
	for i in ${FDE_SEAL_PCR_LIST//,/ }; do
		[ -n "$i" ] || continue
		[ -n "$requested" ] && requested="$requested,$i" || requested="$i"
	done

	# The signed PCR 11 of a UKI does not see the Secure Boot state (PCR
	# 7).  It also does not see a changed command line or addon (PCR 12).
	# With Secure Boot on, systemd-stub ignores an edited command line and
	# refuses unsigned addons.  So only PCR 7 matters.  With Secure Boot
	# off, systemd-stub accepts both, and only PCR 12 sees them.  The user
	# chooses the PCRs, so this is only a warning
	if uki_selected; then
		if is_secure_boot; then
			[[ ",$requested," == *",7,"* ]] || \
				status_warning "UKI is used, but PCR 7 is not in FDE_SEAL_PCR_LIST: the TPM2 does not check that Secure Boot stays enabled"
		else
			[[ ",$requested," == *",12,"* ]] || \
				status_warning "UKI is used without Secure Boot, but PCR 12 is not in FDE_SEAL_PCR_LIST: the TPM2 does not check the kernel command line"
		fi
	fi

	[ -n "$have_policy" ] || {
		status_row "Policy" "$status_policy_backend, the PCRs it binds are unknown"
		return 0
	}

	# For every bound PCR, find three things.  First, how many alternative
	# values the policy accepts.  Second, how far that is from the limit.
	# Past the limit, the PCR is dropped from the next policy.  Third,
	# whether the current value in the TPM2 is one of them.  The TPM2 checks
	# exactly this when the NVIndex must be re-authorized.  Reading it needs
	# two files and no credential
	local values current mark match bound=() unmatched=() details=()
	while read -r i; do
		bound+=("$i")
		values="$(jq -r --argjson p "$i" '.pcrValues[] | select(.pcr == $p) | .values | length' < "$policy")"
		if [ ! -r "/sys/class/tpm/tpm0/pcr-$bank/$i" ]; then
			mark="?"
			match="cannot be read"
		else
			# sysfs writes the values in upper case.  The policy has them in
			# lower case
			current="$(tr '[:upper:]' '[:lower:]' < "/sys/class/tpm/tpm0/pcr-$bank/$i")"
			if jq -e --arg c "$current" --argjson p "$i" \
			      '.pcrValues[] | select(.pcr == $p) | .values | index($c)' \
			      < "$policy" > /dev/null; then
				mark=" "
				match="matches"
			else
				mark="!"
				match="DOES NOT MATCH"
				unmatched+=("$i")
			fi
		fi
		# The mark is the first thing the eye sees.  So it marks the PCR
		# that does not match, not the ones that match
		details+=("   $mark PCR $i: $values value(s), $((8 - values)) before the PolicyOR limit, current value $match")
	done < <(jq -r '.pcrValues[].pcr' < "$policy")

	if [ "${#bound[@]}" -eq 0 ]; then
		status_row "Policy" "$status_policy_backend, bound to no PCR"
	elif [ "${#unmatched[@]}" -eq 0 ]; then
		status_row "Policy" "$status_policy_backend, PCRs $(status_join "${bound[@]}"); the current values match"
	else
		status_row "Policy" "$status_policy_backend, PCRs $(status_join "${bound[@]}"); PCR $(status_join "${unmatched[@]}") DOES NOT MATCH"
	fi

	if [ -n "$arg_full" ]; then
		status_row "Requested PCRs" "${requested:-none}"
		[ "${#details[@]}" -eq 0 ] || printf '%s\n' "  Bound PCRs:" "${details[@]}"
		local nv_index=""
		[ -z "$have_policy" ] || nv_index="$(jq -r '.nvIndex // empty' < "$policy")"
		status_row "NVIndex" "${nv_index:-unknown}"
		if [ -z "$have_policy" ]; then
			status_row "PCR bank" "unknown"
		else
			status_row "PCR bank" "$bank"
		fi
		status_row "Copy in the ESP" "$esp_state"
		if [ -z "$have_policy" ]; then
			status_row "Shim changed" "unknown"
		elif shim_changed; then
			status_row "Shim changed" "yes"
		else
			status_row "Shim changed" "no"
		fi
	fi
	if [ -n "$arg_full" ] && uki_selected; then
		status_row "Kernel entries" "once there is an entry of a UKI, the entries of a kernel and an initrd ask for the password"
	fi

	status_policy_stale="$(policy_stale_pcrs)"

	local missing_list
	missing_list="$(policy_missing_pcrs "$FDE_SEAL_PCR_LIST")"
	# With the UKIs, PCR 9 is out of the policy on purpose
	if uki_selected && [[ ",$missing_list," == *",9,"* ]]; then
		status_row "PCR 9" "not in the policy while the UKIs are selected"
		missing_list="$(remove_pcr "$missing_list" 9)"
	fi
	[ -n "$missing_list" ] || return 0

	# Only a prediction tells why a PCR was dropped.  `systemd-pcrlock
	# predict` takes seconds.  So it runs only when there is something to
	# explain.  The usual report has every requested PCR bound, and stays
	# instant
	local prediction="" pcrlock_status=0
	info "Predicting PCRs to find out why $missing_list were dropped, this takes a few seconds"
	prediction="$(SYSTEMD_LOG_LEVEL=warning pcrlock --pcr="$FDE_SEAL_PCR_LIST" --json=short predict 2> /dev/null)" || pcrlock_status=$?
	[ "$pcrlock_status" -eq 0 ] || prediction=""

	local reason
	for i in ${missing_list//,/ }; do
		if [ -z "$prediction" ]; then
			reason="unknown, the prediction failed"
		elif jq -e --argjson p "$i" '[.sha256[]? | select(.pcr == $p and (.values | length > 8))] | length > 0' \
			<<<"$prediction" > /dev/null; then
			reason="too many alternative values for the PolicyOR"
		elif jq -e --argjson p "$i" '[.sha256[]? | select(.pcr == $p)] | length > 0' \
			<<<"$prediction" > /dev/null; then
			# The PCR can be predicted now, but the policy does not bind it.
			# So the policy is older than the prediction
			reason="predictable now, the policy is older than the components"
		else
			reason="no component matches the event log"
		fi
		status_row "PCR $i" "requested, but $reason, so it is not in the policy"
	done
}

# Replay sha256 digests as PCR 15 extensions, starting from 0.  stdin
# has one digest per line.  Print the final value, or nothing when there
# is no digest
pcr15_replay()
{
	local value="0000000000000000000000000000000000000000000000000000000000000000"
	local digest measured=

	while read -r digest; do
		# TPM_Extend hashes the two binary digests joined together.
		# `printf %b` writes the NUL bytes straight to the pipe.  A command
		# substitution around the binary would drop them.  ${var//;/} cannot
		# replace this sed.  The sed pattern takes every *pair* of characters,
		# and "&" is the pair that matched.  Bash only has globs there, with no
		# repetition and no back-reference
		# shellcheck disable=SC2001
		value="$(printf '%b' "$(sed 's/../\\x&/g' <<<"$value$digest")" | \
				sha256sum | cut -d' ' -f1)"
		measured=1
	done

	[ -z "$measured" ] || echo "$value"
}

# Print the sha256 digests that systemd recorded in PCR 15 for this
# boot, from the log "$1".  Only the events of the type "$2", or all of
# them when "$2" is empty
pcr15_events()
{
	# The log is RFC 7464 JSON-seq.  Every record starts with a 0x1e
	# separator, and jq refuses to read it as JSON.  So tr removes it
	tr -d '\036' < "$1" | \
		jq -r --arg type "$2" \
		   'select(.pcr == 15 and ($type == "" or .content.eventType == $type))
		    | .digests[] | select(.hashAlg == "sha256") | .digest' \
		   2> /dev/null
}

status_pcr15()
{
	if ! grep -q "^[^#]*tpm2-measure-pcr=yes" /etc/crypttab 2> /dev/null; then
		status_row "PCR 15" "not enabled"
		return 0
	fi

	if [ -n "$arg_full" ]; then
		if [ -d /usr/lib/dracut/modules.d/50measure-pcr ]; then
			status_row "Dracut module" "yes"
		else
			status_row "Dracut module" "no"
		fi
	fi

	# This log is the record of what systemd measured in this boot.  A
	# missing log is not an error.  It lives in /run, and it only exists once
	# something was measured.  Nothing is measured at all when the initrd
	# has no generator, or when the generator made no drop-in for the
	# anchor.  Then the slots bound after the anchor do not unseal
	#
	# When the end of the initrd is not measured, the slots bound to the
	# initrd also unseal on the running system (see
	# measure-pcr-boundary.service)
	local log=/run/log/systemd/tpm2-measure.log
	if [ ! -r "$log" ]; then
		status_row "PCR 15" "cannot be told, systemd recorded no measurement"
	elif [ -z "$(pcr15_events "$log" volume-key)" ]; then
		status_row "PCR 15" "NOTHING was measured in this boot"
	elif [ -n "$(pcr15_events "$log" phase)" ]; then
		status_row "PCR 15" "measured in this boot, also the end of the initrd"
	else
		status_row "PCR 15" "the anchor was measured in this boot; the end of the initrd was NOT"
		status_warning "The end of the initrd was NOT measured in this boot, the initrd has no measure-pcr-boundary.service"
	fi
}

status_recovery_pin()
{
	# Report only whether the recovery PIN can be reached, never the PIN.
	# Without it, a policy that no longer matches the PCRs cannot be
	# rewritten.  That is a dead end, not an inconvenience (github issue
	# 250)
	local keyring environment
	IFS=: read -r keyring environment <<<"$(recovery_pin_sources)"

	[ -z "$keyring$environment" ] || status_pin_reachable=1

	local where=()
	[ -z "$keyring" ] || where+=("kernel keyring")
	[ -z "$environment" ] || where+=("environment")

	if [ "${#where[@]}" -eq 0 ]; then
		status_row "Recovery PIN" "not reachable"
	else
		status_row "Recovery PIN" "reachable ($(status_join "${where[@]}"))"
	fi
}

status_service()
{
	local unit="${1:?}"
	local result exit_status timestamp

	result="$(systemctl show -P Result "$unit" 2> /dev/null)" || result=""
	exit_status="$(systemctl show -P ExecMainStatus "$unit" 2> /dev/null)" || exit_status=""
	timestamp="$(systemctl show -P ExecMainExitTimestamp "$unit" 2> /dev/null)" || timestamp=""

	# `Result` is "success" for a unit that never ran.  It is also
	# "success" for a unit that systemd does not know.  Reporting that as a
	# success is worse than saying nothing.  It would answer yes to "did the
	# predictions get updated".  The exit timestamp tells the cases apart
	[ -n "$timestamp" ] || { result=""; exit_status=""; }

	if [ -z "$timestamp" ]; then
		status_row "Last update" "never ran"
	else
		status_row "Last update" "${result}${exit_status:+ (exit $exit_status)}, $timestamp"
	fi
}

# Every file that can configure this run, in the order they are read.
# /etc/sysconfig/bootloader comes first.  It has LOADER_TYPE, SECURE_BOOT
# and UPDATE_NVRAM.  The sdbootutil and fde-tools files come after it, in
# the order of `load_config_file`.  All of them are sourced, so the last
# assignment of a name wins
status_config_files=(/etc/sysconfig/bootloader
		     /usr/etc/default/sdbootutil
		     /etc/default/sdbootutil
		     /usr/etc/default/fde-tools
		     /etc/default/fde-tools
		     /etc/sysconfig/fde-tools)

# Print the last file that assigns this name.  That file decided the
# value.  Print nothing when no file has the name
#
# This uses grep, and does not source the files again.  Sourcing them
# again would run their code a second time, and "status" only reads
status_config_origin()
{
	local name="${1:?}" f origin=""

	for f in "${status_config_files[@]}"; do
		[ -e "$f" ] || continue
		grep -qE "^[[:space:]]*(export[[:space:]]+)?$name=" "$f" 2> /dev/null || continue
		origin="$f"
	done
	echo "$origin"
}

# Print the configuration of this run, and where each value came
# from.  A wrong PCR list can make an entry that does not boot.  So can
# a ROOTFS that does not match the cmdline.  Neither is visible anywhere
# else
status_config()
{
	local read_files=() f
	for f in "${status_config_files[@]}"; do
		[ ! -e "$f" ] || read_files+=("$f")
	done

	echo "Configuration"
	if [ "${#read_files[@]}" -eq 0 ]; then
		status_row "Files read" "none, every value below is a default"
	else
		status_row "Files read" "$(status_join "${read_files[@]}")"
	fi
	status_row "Entry token" "${entry_token:-unknown}"
	status_row "ESP directory" "${esp_root}${esp_dst}"

	# Every line has three fields.  The first is the name of the setting.
	# The second is the CLI argument that overrides it, or "-" when there is
	# none and the setting is only read from a file.  The third says what
	# the setting does.  The name alone is not always enough.  For example,
	# SECURE_BOOT does not describe the firmware.  It only asks to install
	# the shim.  Nothing in sdbootutil sets it from what the firmware
	# enforces
	local name arg note value origin cli where
	while read -r name arg note; do
		[ -n "$name" ] || continue
		value="${!name}"
		[ "$arg" = "-" ] && cli="" || cli="${!arg}"
		origin="$(status_config_origin "$name")"

		if [ -n "$cli" ]; then
			where="from the command line"
		elif [ "$name" = "ROOTFS" ] && is_rootfs_crypt; then
			where="forced, the root device is encrypted"
		elif [ -n "$origin" ] && [ -z "$value" ]; then
			# A file that assigns an empty value is not the same as a name that
			# no file has, even if both end up unset
			where="empty in $origin"
		elif [ -n "$origin" ]; then
			where="from $origin"
		else
			where="not set anywhere, this is the default"
		fi

		printf '  %-25s%s\n' "${name}:" "${value:-(unset)}"
		# What the setting does and where the value came from go on their
		# own line.  The name is not always enough, and both do not fit on one
		# line of a terminal
		echo "      $note; $where"
	done <<-EOF
		FDE_SEAL_PCR_LIST arg_pcr the PCRs to seal against
		ROOTFS arg_rootfs how the cmdline names the root
		ESP_FREE_SPACE arg_esp_free_space percentage of the ESP to keep free
		DEVICETREE_SOURCE arg_devicetree_source device tree blob to copy
		LOADER_TYPE - the boot loader to manage
		SECURE_BOOT - "yes" installs the shim, whatever the firmware does
		UPDATE_NVRAM - "no" keeps sdbootutil out of the EFI variables
		UKI - "yes" (distribution) or "local" UKIs instead of Type #1 entries
		UKI_CMDLINE - "yes" adds the kernel command line of the system to the UKIs
		LAST_WORKING_SNAPSHOTS - extra snapshots to keep in the prediction
	EOF
}

# Compare a binary in the ESP of the version DEPLOYED with the version
# SYSTEM that the system ships.  Print the result in words.  The
# decision is the same as in `bootloader_needs_update`
status_version_text()
{
	local deployed="$1" system="$2"

	if [ -z "$system" ]; then
		echo "the version of the system cannot be read"
		return
	fi

	# The comparison goes to stdout ("261.2 == 261.2").  Only the exit
	# status is needed here
	local status=0
	systemd-analyze compare-versions "$deployed" "$system" > /dev/null 2>&1 || status="$?"
	case "$status" in
		11) echo "newer than the $system of the system" ;;
		12) echo "OUTDATED, the system has $system" ;;
		*)  echo "up to date" ;;
	esac
}

# The warnings of `status`, printed together at the end
status_warnings=()
status_warning()
{
	status_warnings+=("$1")
}

# What the machine booted, and what it will boot next
status_boot()
{
	echo "Boot loader"

	# Compare the version in the ESP with the version that the system
	# ships.  Do the same for the shim.  `install_bootloader` deploys both,
	# and `bootloader_needs_update` counts both.  Each one can be missing.
	# Maybe no boot loader is installed yet, or the snapshot has no boot
	# loader package
	local name deployed="" system="" path="" type
	name="$(bootloader_name 2> /dev/null || echo unknown)"
	deployed="$(bootloader_version 2> /dev/null)" || deployed=""
	path="$(find_bootloader 2> /dev/null)" || path=""
	# Only with a path.  With an empty argument, `bootloader_version`
	# reads the copy in the ESP.  Then it would compare the deployed version
	# with itself
	[ -z "$path" ] || system="$(bootloader_version "$path" 2> /dev/null)" || system=""
	if [ -z "$deployed" ]; then
		type="$name, not found in the ESP"
	else
		type="$name $deployed, $(status_version_text "$deployed" "$system")"
	fi
	local deployed_shim="" system_shim=""
	deployed_shim="$(shim_version 2> /dev/null)" || deployed_shim=""
	if [ -n "$deployed_shim" ]; then
		system_shim="$(shim_version "$(find_shim)" 2> /dev/null)" || system_shim=""
		type+="; shim $(status_version_text "$deployed_shim" "$system_shim")"
	elif is_secure_boot; then
		type+="; no shim"
	fi
	status_row "Type" "$type"

	status_row "UKI" "$(uki_mode_text)"
	[ "${UKI:-}" = "$uki_config" ] || \
		status_warning "/etc/sysconfig/bootloader has UKI=\"$uki_config\", but the TPM2 slots are made for UKI=\"${UKI:-}\": enroll the TPM2 again ('sdbootutil enroll --method tpm2') to change"
	if [ "${UKI:-}" = "yes" ]; then
		local missing
		missing="$(uki_missing_kernels | paste -sd ' ')"
		[ -z "$missing" ] || status_warning "No UKI for the kernels $missing, so they boot as a kernel and an initrd: install their kernel-<flavor>-uki-<variant> packages"
	fi
	# The addon of each entry has the rest of the command line.  It is
	# signed with the local key (see `uki_addon_cmdline`)
	if uki_selected; then
		local problem
		problem="$(dps_root_problem)"
		if [ -n "$problem" ]; then
			status_row "Root discovery" "no, $problem; the shared addon has \"root=\""
		elif [ -e "$(dps_addon_path)" ]; then
			status_row "Root discovery" "yes; the shared addon has the crypttab of the other devices of the initrd"
		else
			status_row "Root discovery" "yes"
		fi
		[ -z "$arg_full" ] || [ ! -e "$(dps_addon_path)" ] || status_row "Shared addon" "$(dps_addon_path)"
		local dps=""
		[ -n "$problem" ] || dps=1
		dps_addon_crypttab_current "$dps" || \
			status_warning "The crypttab in the shared addon of the UKIs is not the one of /etc/crypttab: run 'sdbootutil mkinitrd'"
		if [ -e "$(dps_addon_path)" ]; then
			local others
			others="$(dps_addon_others | paste -sd ' ')"
			[ -z "$others" ] || status_warning "The shared addon of the UKIs changes the boot of the UKIs of other systems too: $others"
		fi
		status_row "Command line" "$(uki_cmdline_text)"
		# The keys.  With --full, print their paths.  Always report a missing
		# key
		if [ -e "$credstore/secureboot-private-key.pem" ]; then
			[ -z "$arg_full" ] || status_row "UKI key" "$secureboot_certificate"
		else
			status_row "UKI key" "not made yet"
		fi
		if [ "$UKI" = "local" ] && grep -qs "^[^#]*tpm2-device" /etc/crypttab; then
			if [ -e "$credstore/tpm2-pcr-initrd-private-key.pem" ]; then
				[ -z "$arg_full" ] || status_row "PCR 11 key" "$pcr_public_key"
			else
				status_row "PCR 11 key" "not made yet"
			fi
		fi
		if is_secure_boot && is_shim_installed && [ -e "$secureboot_certificate" ]; then
			case "$(mok_state)" in
				enrolled) [ -z "$arg_full" ] || status_row "MOK" "the UKI certificate is enrolled" ;;
				pending) status_row "MOK" "enrolled at the next boot, in MokManager" ;;
				*) status_row "MOK" "the UKI certificate is not enrolled" ;;
			esac
		fi
	fi

	# This takes its own copy of the entry list, and does not call
	# `update_entries`.  `update_entries` writes "$entryfile", and the rest
	# of the report reads that file for other purposes
	local entries
	entries="$(bootctl list --json=short 2> /dev/null)" || entries="[]"
	[ -n "$entries" ] || entries="[]"

	# `bootctl` sets "isSelected" when the entry ID matches
	# "LoaderEntrySelected".  grub2-bls spells the variable differently, so
	# nothing matches there, and "isSelected" is always null.  So the ID is
	# also compared here, through `entry_key`.  This is the same workaround
	# as in `list_entries`
	local selected="" key="" booted=""
	selected="$(bli_efi_var_get "LoaderEntrySelected" 2> /dev/null)" || selected=""
	key="$(entry_key "$selected")"
	booted="$(jq -r --arg k "$key" \
		     'first(.[] | select(.isSelected == true
					 or (.id | sub("\\.conf$"; "")) == $k)
			   | .id) // empty' <<<"$entries")"
	# When no entry matches, report the raw variable.  The machine may
	# have booted something that the ESP no longer has.  Then the name is
	# the answer, and "unknown" is not
	[ -n "$booted" ] || booted="$selected"

	# Older versions of grub2-bls do not write the variable at all, so
	# the code above finds nothing on those systems.  Then look for the entry that
	# describes the running system.  It must have the kernel release.  When
	# there are snapshots, it must also have the subvolume of the running
	# snapshot.  Only a single match is taken, because two entries that
	# describe the same thing cannot be told apart here
	#
	# This finds the entry that was booted, unless it was rewritten since.
	# So it is useful, but it is labelled as a guess
	local guess=""
	if [ -z "$booted" ]; then
		local subvol=""
		[ -z "$have_snapshots" ] || subvol="${subvol_prefix}/.snapshots/${root_snapshot}/snapshot"
		booted="$(jq -r --arg k "$(uname -r)" --arg s "$subvol" --arg n "$root_snapshot" \
			     '[.[] | select(.type? == "type1")
				   | select((.version // "") | endswith($k))
				   | select($s == "" or ((.options // "") | contains("rootflags=subvol=" + $s))
					    or ((.id // "") | test("-commit_" + $n + "[.@+]")))]
			      | if length == 1 then .[0].id else empty end' <<<"$entries")"
		[ -z "$booted" ] || guess=" (from the running kernel, the boot loader reported nothing)"
	fi

	# Find the entries that name a file that the ESP does not have.  They
	# are checked against the two entries that this section names.  Saying
	# "Next boot: X" about an entry that stops at the firmware is not only
	# incomplete.  It is wrong
	status_dangling="$(dangling_entries <<<"$entries")"

	if [ -n "$booted" ]; then
		local note=""
		# This is only worth saying about a guess.  The entry that really
		# booted had its files at that time.  The entry may have been
		# rewritten since
		! status_is_dangling "$booted" || note=" -- and no longer boots"
		status_row "Booted entry" "$booted$guess$note"
	else
		status_row "Booted entry" "unknown, the boot loader reported none"
	fi

	# The boot loader uses a one shot entry on the next boot, and then
	# removes it.  So while it is set, the one shot entry boots next, not
	# the default
	local oneshot="" default=""
	oneshot="$(bli_efi_var_get "LoaderEntryOneShot" 2> /dev/null)" || oneshot=""
	default="$(get_default_entry 2> /dev/null)" || default=""

	local next="${oneshot:-$default}"
	local broken=""
	! status_is_dangling "$next" || broken=" -- DOES NOT BOOT, it names a file that is not in the ESP"
	# The default of snapper and btrfs is not what the boot loader reads.
	# The two only have to agree.  When they do not, each tool reports its
	# own default, and none of them looks wrong alone.  So the mismatch is
	# reported here, where the default entry is named, and nowhere else
	local diverged=""
	if [ -n "$have_snapshots" ] && [ -n "$default" ]; then
		local esp_snapshot="" btrfs_snapshot=""
		esp_snapshot="$(entry_snapshot "$default" <<<"$entries")"
		btrfs_snapshot="$(default_snapper_snapshot)"
		[ -z "$esp_snapshot" ] || [ -z "$btrfs_snapshot" ] || [ "$esp_snapshot" = "$btrfs_snapshot" ] || \
			diverged=" -- boots snapshot $esp_snapshot, while snapper and btrfs default to $btrfs_snapshot; run 'sdbootutil set-default-snapshot $esp_snapshot' to align them"
	fi

	if [ -n "$oneshot" ]; then
		status_row "Next boot" "$oneshot (one shot, and then ${default:-the default})$broken$diverged"
	elif [ -n "$default" ] && [ "$(entry_key "$default")" = "$(entry_key "$booted")" ] && [ -z "$guess$broken$diverged" ]; then
		status_row "Next boot" "the same"
	else
		status_row "Next boot" "${default:-unknown, no default is set}$broken$diverged"
	fi

	[ -z "$arg_full" ] || {
		# Count only the real entries.  The list also has the entries that
		# the boot loader adds by itself, like "Reboot Into Firmware
		# Interface".  Counting those does not help anybody
		local count=0 dangling=0
		count="$(jq -r '[.[] | select(.type? == "type1")] | length' <<<"$entries")"
		[ -z "$status_dangling" ] || dangling="$(grep -c . <<<"$status_dangling")"
		if [ "$dangling" -eq 0 ]; then
			status_row "Entries" "$count"
		elif [ "$dangling" -eq 1 ]; then
			status_row "Entries" "$count, of which 1 does not boot"
		else
			status_row "Entries" "$count, of which $dangling do not boot"
		fi
		local timeout=""
		timeout="$(get_timeout 2> /dev/null)" || timeout=""
		status_row "Menu timeout" "${timeout:-not set}"
	}
}

status_system()
{
	echo "System"
	status_row "ESP" "$esp_root"
	# The state of the firmware.  This is not the SECURE_BOOT of the
	# configuration.  SECURE_BOOT only asks to install the shim.  It never
	# looks at what the firmware enforces
	if is_secure_boot; then
		status_row "Secure Boot" "enabled in the firmware"
	else
		status_row "Secure Boot" "disabled in the firmware"
	fi
	# Details for --full.  The boot loader section says if the shim
	# is up to date
	if [ -n "$arg_full" ]; then
		if is_shim_installed; then
			status_row "Shim" "installed"
		else
			status_row "Shim" "not installed"
		fi
		if is_transactional; then
			status_row "Transactional" "yes"
		else
			status_row "Transactional" "no"
		fi
	fi
	# The lockout explains why a device that is enrolled and predicted
	# correctly can still stay closed
	if ! have_tpm2; then
		status_row "TPM2" "no"
	elif in_lockout 2> /dev/null; then
		status_row "TPM2" "yes (IN LOCKOUT)"
	else
		status_row "TPM2" "yes"
	fi
}

fde_status()
{
	status_system

	[ -z "$arg_full" ] || { echo; status_config; }

	echo
	status_boot
	echo
	status_devices
	echo
	echo "TPM2"
	status_policy
	status_pcr15
	status_recovery_pin
	status_service sdbootutil-update-predictions.service

	# An entry that names a file that the ESP does not have is hidden
	# everywhere else.  `bootctl list` prints it, and the boot loader offers
	# it.  The failure is only a firmware message, on the boot that picked
	# it.  So the report names these entries.  The reader has no other way
	# to find them
	if [ -n "$status_dangling" ]; then
		local id path snapshot kernel_version missing
		while IFS='|' read -r id path snapshot kernel_version missing; do
			status_warning "The boot entry $id (${snapshot:+snapshot $snapshot, }$kernel_version) is missing $missing, so it does not boot: run 'sdbootutil cleanup --repair' to write it again from the kernel"
		done <<<"$status_dangling"
	fi

	# A policy with no device behind it is not an error.  But the reader
	# never expects it from "Policy: pcrlock".  A partial unenroll leaves
	# it.  Then the whole TPM2 section describes something that opens
	# nothing
	[ -z "$status_policy_backend" ] || [ -n "$status_tpm2_device" ] || \
		status_warning "There is a TPM2 policy, but no device has a TPM2 keyslot.  Nothing is opened by the TPM2, and the TPM2 part above describes a leftover"

	# A stale PCR has two opposite cases, and the difference is the whole
	# answer.  It is routine when the next `update-predictions` rewrites the
	# policy.  It is a dead end when it cannot.  Without a recovery PIN,
	# re-authorizing the NVIndex needs the current PCRs to match the *old*
	# policy (github issue 250)
	if [ -n "$status_policy_stale" ]; then
		local i line
		if [ -n "$status_pin_reachable" ]; then
			status_warning "PCR $status_policy_stale no longer match the policy.  The next 'sdbootutil update-predictions' rewrites it with the reachable recovery PIN, trusting the current boot path"
			for i in ${status_policy_stale//,/ }; do
				status_warning "PCR $i measures $(pcr_meaning "$i")"
			done
		else
			status_warning "PCR $status_policy_stale no longer match the policy, and no recovery PIN is reachable, so every 'update-predictions' from now on fails the same way"
			while IFS= read -r line; do
				status_warning "${line#WARNING: }"
			done < <(explain_pcrlock_recovery "$status_policy_stale" 2>&1)
		fi
	fi

	if [ "${#status_warnings[@]}" -gt 0 ]; then
		echo
		echo "Warnings"
		local warning
		for warning in "${status_warnings[@]}"; do
			echo "  $warning"
		done
	fi

	# This line is only for a person who reads the terminal.  A report
	# that is collected is redirected, and there the line is noise
	[ -z "$interactive" ] || [ -n "$arg_full" ] || {
		echo
		echo "Run 'sdbootutil status --full' for the full report"
	}
}

eval_bootctl()
{
	# XXX: bootctl should have json output for that too
	# shellcheck disable=SC2016
	eval "$(bootctl 2> /dev/null | sed -ne 's/Firmware Arch: *\(\w\+\)/firmware_arch="\1"/p;s/ *token: *\(\w\+\)/entry_token="\1"/p')"
	esp_root="$(bootctl --print-esp-path)"
	boot_root="$(bootctl --print-boot-path)"
}

bootloader_name()
{
	info "Checking the bootloader name"

	if is_sdboot "${1:-$root_snapshot}"; then
		echo "systemd-boot"
	elif is_grub2_bls "${1:-$root_snapshot}"; then
		echo "grub2-bls"
	else
		err "Bootloader not detected"
	fi
}

set_image_name() {
	[ -z "$image" ] || return 0

	declare -gA arch_image_map=(
		[x64]="vmlinuz"
		[aa64]="Image"
		[riscv64]="Image"
	)

	if [ -n "${arch_image_map[$firmware_arch]}" ]; then
		image="${arch_image_map[$firmware_arch]}"
	else
		err "Unsupported architecture $firmware_arch"
	fi
}

define_commands() {
	declare -gA commands=(
		[install]=""
		[needs-update]=""
		[update]=""
		[force-update]=""
		[add-kernel]="kernel"
		[remove-kernel]="kernel"
		[cleanup]=""
		[set-default-snapshot]=""
		[add-all-kernels]=""
		[mkinitrd]=""
		[remove-all-kernels]=""
		[is-installed]=""
		[list-snapshots]=""
		[list-entries]=""
		[list-kernels]=""
		[list-devices]=""
		[status]=""
		[show-entry]="kernel"
		[update-entry]="kernel"
		[update-all-entries]=""
		[is-bootable]=""
		[set-default]="id"
		[get-default]=""
		[set-timeout]="seconds"
		[get-timeout]=""
		[print-loader-path]=""
		[enroll]=""
		[unenroll]=""
		[update-predictions]=""
		[sync-pcrlock-policy]=""
		[bootloader]=""
	)
}

define_options() {
	declare -gA options_with_arg=(
		[help]=""
		[version]=""
		[verbose]=""
		[start-trace-code]=""
		[stop-trace-code]=""
		[esp-path]="_path"
		[entry-token]="_path"
		[arch]="_arch_name"
		[image]="_image_name"
		[entry-keys]="_find_kernels"
		[no-variables]=""
		[no-reuse-initrd]=""
		[no-random-seed]=""
		[all]=""
		[sync]=""
		[portable]=""
		[secure-boot]=""
		[removable]=""
		[only-default]=""
		[default-snapshot]=""
		[ask-key]=""
		[ask-pin]=""
		[ask-recovery-pin]=""
		[ask-pw]=""
		[ask-current-pw]=""
		[method]="_method"
		[no-measure-pcr]=""
		[pcr]="_none"
		[devices]="_devices"
		[rootfs]="_rootfs"
		[rootfs-data]="_rootfs_data"
		[esp-free-space]="_esp_free_space"
		[devicetree-source]="_file"
		[force]=""
		[strict]=""
		[disable-predictions]=""
		[full]=""
		[repair]=""
	)
	opts_long=""
	for opt in "${!options_with_arg[@]}"; do
		if [ "${options_with_arg[$opt]}" ]; then
			opts_long+="${opt}:,"
		else
			opts_long+="${opt},"
		fi
	done
	opts_long="${opts_long%,}"
}

# Two runs at the same time race over the ESP, the boot entries and
# /var/lib/pcrlock.d.  This happens at boot, when health-checker calls
# set-default-snapshot while sdbootutil-update-predictions.service is
# running.  The lock is released when the process exits.  Without the
# permission to take the lock, the command would fail later anyway
#
# The directory is only for root, like in the snapper plugin.  Any user
# that can open the lock can also hold it, and block every run
take_lock()
{
	{ mkdir -p /run/sdbootutil && chmod 700 /run/sdbootutil; } 2> /dev/null || return 0
	exec {lock_fd}> /run/sdbootutil/lock || return 0
	flock -n "$lock_fd" && return 0
	info "Waiting for another sdbootutil to finish"
	flock -w 600 "$lock_fd" || err "Another sdbootutil has been running for 10 minutes"
}

####### main #######

if [ "$1" = "_print_bash_completion_data" ]; then
	declare -f set_image_name
	declare -f eval_bootctl
	declare -f define_commands
	declare -f define_options
	exit 0
fi

define_options
getopt_tmp=$(getopt -o hv --long "$opts_long" -n "${0##*/}" -- "$@")
eval set -- "$getopt_tmp"

while true ; do
	case "$1" in
		-h|--help) helpandquit ;;
		--version) echo "sdbootutil $version"; exit 0 ;;
		-v|--verbose) verbose=$((++verbose)); shift ;;
		--start-trace-code) shift ;;
		--stop-trace-code) shift ;;
		--esp-path) arg_esp_path="$2"; shift 2 ;;
		--arch) arg_arch="$2"; shift 2 ;;
		--entry-token) arg_entry_token="$2"; shift 2 ;;
		--image) image="$2"; shift 2 ;;
		--entry-keys) IFS=',' read -r -a arg_entry_keys <<<"$2"; shift 2 ;;
		--no-variables) arg_no_variables=1; shift ;;
		--no-reuse-initrd) arg_no_reuse_initrd=1; shift ;;
		--no-random-seed) arg_no_random_seed=1; shift ;;
		--all) arg_all_entries=1; shift ;;
		--sync) arg_sync=1; shift ;;
		--portable) arg_portable=1; shift ;;
		--removable) arg_portable=1; shift ;;
		--secure-boot) arg_secure_boot=1; shift ;;
		--only-default) arg_only_default=1; shift ;;
		--default-snapshot) arg_default_snapshot=1; shift ;;
		--ask-key) arg_ask_key=1; shift ;;
		--ask-pin) arg_ask_pin=1; shift ;;
		--ask-recovery-pin) arg_ask_recovery_pin=1; shift ;;
		--ask-pw) arg_ask_pw=1; shift ;;
		--ask-current-pw) arg_ask_current_pw=1; shift ;;
		--method) arg_method="$2"; shift 2 ;;
		--no-measure-pcr) arg_no_measure_pcr=1; shift ;;
		--pcr) arg_pcr="$2"; shift 2 ;;
		--devices) IFS=',' read -r -a tracked_devices <<<"$2"; shift 2 ;;
		--rootfs) arg_rootfs="$2"; shift 2 ;;
		--rootfs-data) arg_rootfs_data="$2"; shift 2 ;;
		--esp-free-space) arg_esp_free_space="$2"; shift 2 ;;
		--devicetree-source) arg_devicetree_source="$2"; shift 2 ;;
		--force) arg_force=1; shift ;;
		--strict) arg_strict=1; shift ;;
		--disable-predictions) arg_disable_predictions=1; shift ;;
		--full) arg_full=1; shift ;;
		--repair) arg_repair=1; shift ;;
		--) shift ; break ;;
		*) echo "Internal error!" ; exit 1 ;;
	esac
done

if [ -z "$SYSTEMD_LOG_LEVEL" ] && [ "${verbose:-0}" -gt 1 ]; then
	if [ "$verbose" -gt 2 ]; then
		SYSTEMD_LOG_LEVEL=debug
	else
		SYSTEMD_LOG_LEVEL=info
	fi
	export SYSTEMD_LOG_LEVEL
fi

# The variables of the help (PW, KEY, PIN) are read from the
# environment, so they must be set before the command name.  `getopt`
# moves them to the end of the argument list.  There they look like an
# optional [SNAPSHOT], and they are silently ignored.  For example,
# this command drops the password instead of using it
#
#   sdbootutil enroll PW=secret --method=password
for variable_arg in "$@"; do
	[[ "$variable_arg" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] || continue
	err "\"$variable_arg\" is not a command nor an option. Set the variable before the command name: ${variable_arg%%=*}=... ${0##*/} ..."
done

define_commands
if [ -z "$1" ]; then
	helpandquit
elif [ -z ${commands["$1"]+yes} ]; then
	err "unknown command $1"
fi

[ -n "$arg_esp_path" ] && export SYSTEMD_ESP_PATH="$arg_esp_path"

eval_bootctl

case "$1" in
	is-installed|needs-update|list-*|status|show-entry|is-bootable|get-*|print-loader-path|bootloader) ;;
	*) take_lock ;;
esac

root_subvol=""
subvol_prefix=""
root_subvol_err=
is_btrfs_snapshots=
if [ "$(stat -f -c %T /)" = "btrfs" ] && [ -d /.snapshots ]; then
	is_btrfs_snapshots=1
	# `btrfs` lives in /usr/sbin, and not every PATH has it.  Without
	# this check, the only symptom is an empty `root_subvol`.  It is
	# reported below as a generic "Can't determine root subvolume", which
	# hides the real cause
	command -v btrfs > /dev/null || \
		err "btrfs command not found. Install btrfsprogs or add /usr/sbin to the PATH"
	# Keep the error of the command.  It is reported together with the
	# failed detection below
	root_subvol=$(btrfs subvol show / 2> "$tmpdir/btrfs.err" | head -1)
	root_subvol_err="$(cat "$tmpdir/btrfs.err")" || :
	rm -f "$tmpdir/btrfs.err"
	subvol_prefix="${root_subvol%/.snapshots/*}"
	# "/.snapshots" alone is not enough.  The system boots from a
	# snapshot only when the root subvolume is
	# "<prefix>/.snapshots/<N>/snapshot".  This is also the only shape that
	# `subvol_prefix` and `running_snapshot` can parse.  A plain "@" root
	# with snapper installed (no rollback layout) is a regular system.
	# Treating it as a snapshot system builds paths like
	# "@/.snapshots/@/snapshot", which do not exist
	[[ "$root_subvol" =~ ^.+/\.snapshots/[0-9]+/snapshot$ ]] && have_snapshots=1
elif [ -e /.snapshots/1/info.xml ]; then
	# This is an image build (mkosi).  The root is not btrfs, but part of
	# the snapshots directory is there.  `subvol_prefix` is set to the
	# value that openSUSE uses
	in_buildroot=1
	subvol_prefix="@"
fi

root_snapshot=""
running_snapshot=""
if [ -n "$have_snapshots" ]; then
	running_snapshot="${root_subvol#"${subvol_prefix}"/.snapshots/}"
	running_snapshot="${running_snapshot%/snapshot}"
	if [ -n "$arg_default_snapshot" ]; then
		[ -s "$snapperfile" ] || update_snapper
		read -r root_snapshot <<<"$(jq -r '.root[]|select(.default==true)|.number' < "$snapperfile")"
	else
		root_snapshot="$running_snapshot"
	fi
	applied_snapshot="$(detect_applied_snapshot)"
elif [ -n "$in_buildroot" ]; then
	root_snapshot="1"
fi

if [ -n "$arg_esp_path" ] && [ "$esp_root" != "$arg_esp_path" ]; then
	err "Mismatch of ESP path"
fi
[ -n "$arg_arch" ] && firmware_arch="$arg_arch"

[ -n "$esp_root" ] || err "No ESP detected. Legacy system?"
[ -n "$root_subvol" ] || [ -z "$is_btrfs_snapshots" ] || \
	err "Can't determine root subvolume${root_subvol_err:+: $root_subvol_err}"
[ -n "$firmware_arch" ] || err "Can't determine firmware arch"
set_image_name

mountpoint -q "$esp_root" || warn "$esp_root is not a valid mountpoint"

dbg_var "root_snapshot"
dbg_var "running_snapshot"
dbg_var "applied_snapshot"
dbg_var "esp_root"
dbg_var "boot_root"

# shellcheck disable=SC1091
[ -e /etc/sysconfig/bootloader ] && . /etc/sysconfig/bootloader

if is_sdboot; then
	esp_dst="/EFI/systemd"
elif is_grub2_bls; then
	set_os_release "${root_snapshot}"
	# shellcheck disable=SC2154
	read -r -a name <<<"${os_release_NAME,,}"
	esp_dst="/EFI/${name[0]}"
else
	msg="Bootloader not detected"
	[ -z "$LOADER_TYPE" ] || msg+=". /etc/sysconfig/bootloader has LOADER_TYPE=\"$LOADER_TYPE\", but only \"systemd-boot\" or \"grub2-bls\" are recognized."
	err "$msg"
fi

# Removable media layout is described in
# https://github.com/rhboot/shim/blob/main/README.fallback
if [ -n "$arg_portable" ]; then
	if [ -d "${esp_root}${esp_dst}" ]; then
		err "Bootloader is already installed permanently"
	fi
	esp_dst="/EFI/BOOT"
fi

# For every operation other than install, esp_dst must already
# exist.  When it does not, this is a removable installation
if [ "$1" != "install" ] && [ ! -d "${esp_root}${esp_dst}" ]; then
	info "Removable installation detected"
	esp_dst="/EFI/BOOT"
	arg_portable=1
fi

dbg_var "esp_dst"

assert_uki_config
settle_uki_mode

if [ "$SECURE_BOOT" = "yes" ] || is_shim_installed; then
	arg_secure_boot=1
fi

if [ "$UPDATE_NVRAM" = "no" ]; then
	if has_efivars; then
		warn 'The system has EFI variables but UPDATE_NVRAM is set to "no"'
	fi
	arg_no_variables=1
fi

# If there is a config file, load it.  If not, but the boot loader is
# installed, create a default one from the CLI arguments.  Otherwise,
# use default values.
#
# When the config file misses some values, the load code uses default
# values.
if is_config_file; then
	load_config_file
elif is_installed; then
	create_default_config_file
else
	set_default_config_values
fi

# Save the initial components before some actions replace them (a
# new initrd, a new entry, etc)
if [ "$SDB_ADD_INITIAL_COMPONENT" = "1" ]; then
	backup_initial_components
fi

case "$1" in
	install)
		assert_snapshot "$2"
		install_bootloader "${2:-$root_snapshot}"
		install_extra_entries "${2:-$root_snapshot}"
		create_default_config_file ;;
	needs-update)
		bootloader_needs_update "${2:-$root_snapshot}" ;;
	update)
		assert_snapshot "$2"
		bootloader_update "${2:-$root_snapshot}" ;;
	force-update)
		if is_installed; then
			assert_snapshot "$2"
			install_bootloader "${2:-$root_snapshot}"
		else
			:
		fi ;;
	bootloader)
		bootloader_name "${2:-$root_snapshot}" ;;
	add-kernel)
		assert_snapshot "$3"
		install_kernel "${3:-$root_snapshot}" "$2" ;;
	add-all-kernels)
		assert_snapshot "$2"
		install_all_kernels "${2:-$root_snapshot}" ;;
	mkinitrd)
		assert_snapshot "$2"
		arg_no_reuse_initrd=1
		install_all_kernels "${2:-$root_snapshot}" ;;
	remove-kernel)
		assert_snapshot "$3"
		remove_kernel "${3:-$root_snapshot}" "$2" ;;
	remove-all-kernels)
		assert_snapshot "$2"
		remove_all_kernels "${2:-$root_snapshot}" ;;
	cleanup)
		cleanup_entries "${2:-}" ;;
	set-default-snapshot)
		assert_snapshot "$2"
		set_default_snapshot "${2:-$root_snapshot}" ;;
	is-installed)
		if is_installed; then
			info "systemd-boot was installed using sdbootutil"
			exit 0
		else
			info "not installed using this tool"
			exit 1
		fi ;;
	list-kernels)
		list_kernels "${2:-$root_snapshot}" ;;
	list-entries)
		list_entries "${2:-}" ;;
	list-snapshots)
		list_snapshots ;;
	list-devices)
		list_devices ;;
	status)
		fde_status ;;
	show-entry)
		show_entry_fields "${3:-$root_snapshot}" "$2" ;;
	update-entry)
		assert_snapshot "$3"
		update_entry "${3:-$root_snapshot}" "$2" ;;
	update-all-entries)
		assert_snapshot "$2"
		update_all_entries "${2:-$root_snapshot}" ;;
	is-bootable)
		is_bootable "${2:-$root_snapshot}" ;;
	set-default)
		assert_snapshot "$2"
		set_default_entry "$2" ;;
	get-default)
		get_default_entry "$2" ;;
	set-timeout)
		set_timeout "$2" ;;
	get-timeout)
		get_timeout "$2" ;;
	print-loader-path)
		print_loader_path ;;
	enroll)
		enroll ;;
	unenroll)
		unenroll ;;
	update-predictions)
		update_predictions=1 ;;
	sync-pcrlock-policy)
		sync_pcrlock_policy ;;
	*)
		helpandquit ;;
esac

# Once per command, not per kernel: it reads every entry
[ -z "$cleanup_pending" ] || bootctl_cleanup

[ -z "$update_predictions" ] || [ -n "$arg_disable_predictions" ] || {
	generate_tpm2_predictions && rebind_tpm2_slots
}
