#!/bin/bash
# Puts a kernel of plinius-kernel in place, the way grub keeps a "previous kernel" entry on other
# systems. Called by the pacman hooks and by plinius-kernel-boot.service.
#
# A new kernel becomes the default at once: install writes it to boot<slot>, and the kernel that
# was there is kept as the fallback. With the boot menu on the memory card (Android Boot Manager,
# db/entries/real.conf starts the Arch on the phone's own storage), the fallback is the entry
# "plinius-previous", with the ramdisks of the phone's vendor_boot/init_boot and their command line,
# and the menu's autostart points to "Arch Linux" (real.conf) again: the menu remembers an entry
# chosen by hand, the fallback for one, and would keep starting it. If the new kernel does not come
# up, choosing "Arch Linux (previous kernel ...)" in the menu starts the old one. Without the card,
# "restore" writes the fallback back.
#
# An Arch on memory card partitions (set up by Plinius Boot) starts from its own entry in the boot
# menu, not from boot<slot>. Its command line names its card partition: systempart=, or datapart=
# alone when the system is rootfs.img on its (encrypted) data partition. There a new kernel goes into
# the entry, and the kernel that was there becomes "<entry>-kernel-previous", with the entry's own
# ramdisk, device tree and command line. The name leaves the fallback entry of an Arch on the phone's
# storage alone. plinius-bootcheck judges these entries as its own, so what is written there is
# reported to it as well.
#
# Trial entries of older versions ("plinius-trial", "<entry>-kernel-trial", state "trial") are
# dropped by the next install.
#
# A new system from image/mkimage.sh starts with the package's kernel already: the image carries it
# in place of UT's 6.1.145, and an older plinius-kernel as the fallback (kept, named as previous).
# Its first start records the kernel and gives the fallback what an update would have made: the boot
# image and card entry of the previous kernel (boot, once: no kernel recorded as installed yet). A
# system that starts with another kernel gets the package's installed as an update.
#
# The fallback is always the kernel that last started for sure: the one that runs from boot<slot>
# (or the entry) when the new one is written, or, when the system runs on the fallback because the
# installed kernel does not work, the fallback stays and only the installed one is replaced.
#
# Each kernel has its own GKI modules (system_dlkm.img, mounted for the Android container by
# "dlkm") and out-of-tree modules (/usr/lib/plinius/modules/<release>, loaded by plinius-kmod).
# Before pacman removes a release that is still installed or the fallback, "keep" copies it to
# /var/lib/plinius-kernel/kept/<release>, where the image also puts its fallback. UT's 6.1.145
# needs nothing kept: its modules are the original system_dlkm.img and plinius-kmod's.
#
# The slot never changes: lk would then start the other system (Volla OS of the delivery).
#
# Usage: plinius-kernel-install hook       (pacman, after install/upgrade; boot.img paths on stdin)
#        plinius-kernel-install keep       (pacman, before upgrade/removal)
#        plinius-kernel-install install RELEASE
#        plinius-kernel-install boot       (plinius-kernel-boot.service: set up the package's kernel
#                                           on a new system)
#        plinius-kernel-install dlkm       (mount-android-partitions: this kernel's GKI modules)
#        plinius-kernel-install restore    (fallback back into boot<slot>)
#        plinius-kernel-install status
set -euo pipefail

lib=/usr/lib/plinius/kernel
avb=$lib/plinius-kernel-avb
kmods=/usr/lib/plinius/modules
state=/var/lib/plinius-kernel
kept=$state/kept
dlkm=/var/lib/lxc/android/system_dlkm.img
card=/dev/mmcblk0p1
mnt=/run/plinius-kernel/card
previous=plinius-previous
# The trial entry of older versions, dropped by install
trial=plinius-trial

die() { echo "plinius-kernel: $*" >&2; exit 1; }
say() { echo "plinius-kernel: $*"; }

# --- state: one release name per file (installed = in boot<slot>, previous = fallback) ---
get() { cat "$state/$1" 2>/dev/null || true; }
put() { install -d -m 700 "$state"; echo "$2" > "$state/$1.new"; mv "$state/$1.new" "$state/$1"; }
unset_state() { rm -f "$state/$1"; }

# The active slot as the bootloader reports it ("_a" or "_b"). A start from a card entry may come
# without bootconfig, so the slot of the last normal start is remembered.
slot() {
	local s
	s=$(sed -n 's/^androidboot.slot_suffix = "\(_[ab]\)"$/\1/p' /proc/bootconfig 2>/dev/null || true)
	if [[ $s == _a || $s == _b ]]; then
		put slot "$s"
	else
		s=$(get slot)
	fi
	[[ $s == _a || $s == _b ]] || die "active slot unknown (androidboot.slot_suffix in /proc/bootconfig)"
	echo "$s"
}

# Role of the running start: previous (fallback entry on the card), or empty (boot partition)
role() { sed -n 's/.*\bplinius\.kernel=\([a-z]*\).*/\1/p' /proc/cmdline; }

# The word of the command line that names the card partition of an Arch on the memory card:
# systempart=, or datapart= alone for a system in rootfs.img on its data partition there. Empty for
# the Arch on the phone's storage, which names neither.
card_word() {
	local w sys= data=
	for w in $(cat /proc/cmdline); do
		case $w in
		systempart=?*) sys=$w ;;
		datapart=/dev/mmcblk*) data=$w ;;
		esac
	done
	echo "${sys:-$data}"
}

# An Arch on memory card partitions has its kernel in its own card entry
on_card_system() { [[ -n $(card_word) ]]; }

# Release of the kernel inside a boot image (gzip-compressed Image after the 4 KiB header), or of
# a kernel file of a card entry (gzip-compressed or plain Image)
image_release() {
	python3 - "$1" <<-'EOF'
	import gzip, re, struct, sys
	d = open(sys.argv[1], 'rb').read()
	k = d
	if d[:8] == b'ANDROID!':
	    size, = struct.unpack_from('<I', d, 8)
	    k = d[4096:4096 + size]
	if k[:2] == b'\x1f\x8b':
	    k = gzip.decompress(k)
	m = re.search(rb'Linux version ([0-9]+\.[0-9]+\.[0-9]+[^ ]*) \(', k)
	print(m.group(1).decode() if m else 'unknown')
	EOF
}

# --- partitions ---
boot_part() { echo "/dev/disk/by-partlabel/boot$(slot)"; }

# Writes an image to a partition and reads it back; the rest of the partition stays as it was
write_part() {
	local img=$1 part=$2 size
	size=$(stat -c %s "$img")
	(( size <= $(blockdev --getsize64 "$part") )) || die "$img does not fit into $part"
	dd if="$img" of="$part" bs=1M conv=fsync,notrunc status=none
	cmp -n "$size" "$img" "$part" >/dev/null || die "$part does not hold $img after writing"
}

# Writes a boot image to boot<slot> with the partition's AVB data kept valid (plinius-kernel-avb:
# the vbmeta block moves behind the image, its hash descriptor gets the image's size and digest).
# A valid block is kept in $state/boot-vbmeta.bin; without one, nothing is written. A partition
# without a footer gets the image alone, as before.
write_boot() {
	local img=$1 part=$2 out=$state/boot-new.img
	mkdir -p "$state"
	python3 "$avb" "$img" "$part" "$out" "$state/boot-vbmeta.bin" ||
		die "$img: the AVB data of $part could not be kept, nothing written"
	write_part "$out" "$part"
	rm -f "$out"
}

# Copies the whole partition into a file, through a rename
dump_part() {
	local part=$1 out=$2
	dd if="$part" of="$out.new" bs=1M status=none
	mv "$out.new" "$out"
}

# --- releases: where a kernel's files are ---
release_dir() {
	if [[ -d $lib/$1 ]]; then echo "$lib/$1"
	elif [[ -d $kept/$1 ]]; then echo "$kept/$1"
	fi
}

# --- card: Android Boot Manager ---
have_card() {
	# debugfs ends with 0 also for a missing file or a card it cannot read: only its "Inode:"
	# line says the boot menu is there. grep reads all of it (-q could end debugfs with
	# SIGPIPE, which pipefail takes as a failure).
	[[ -b $card ]] && debugfs -c -R 'stat /db/entries/real.conf' "$card" 2>/dev/null |
		grep '^Inode:' >/dev/null
}

# The card's boot partition is not encrypted: whoever had the card in hand may have put symlinks,
# device files or paths with ".." on it, pointing at the phone's own files (/etc/shadow), which
# root would then copy onto the card or overwrite. It is used only through a mount that follows no
# symlink and takes no device file, set-uid bit or program from it: a mount of the card elsewhere
# (Files) only when it has these options, else the card is mounted once more at $mnt. Each name
# taken from the card is checked besides (card_check), also for a mount made by someone else.
card_opts=nosymfollow,nodev,nosuid,noexec
card_mount() {
	local at opts o ok
	while read -r at opts; do
		ok=1
		for o in ${card_opts//,/ }; do
			[[ ,$opts, == *,$o,* ]] || ok=
		done
		if [[ -n $at && -n $ok ]]; then
			echo "$at"
			return
		fi
	done < <(findmnt -rn -o TARGET,OPTIONS -S "$card" || true)
	# A mount of ours without these options (an older version, cut off) goes first
	card_umount
	install -d -m 700 "$mnt"
	mount -t ext4 -o "$card_opts" "$card" "$mnt"
	echo "$mnt"
}

card_umount() {
	sync
	if findmnt -rno TARGET "$mnt" >/dev/null 2>&1; then umount "$mnt"; fi
}

# --- names taken from the card: plain names below its root, no symlink on the way ---
# A file of an entry (its "linux" line): DIR/FILE of plain names, neither starting with a dot
card_rel_ok() { [[ $1 =~ ^[A-Za-z0-9_][A-Za-z0-9_.-]*/[A-Za-z0-9_][A-Za-z0-9_.-]*$ ]]; }

# The name of an entry (its file in db/entries without .conf)
entry_name_ok() { [[ $1 =~ ^[A-Za-z0-9_][A-Za-z0-9_.-]*$ ]]; }

# card_file_ok ROOT REL: REL (DIR/FILE) below ROOT is a regular file or missing, in a directory
# that is a real one or missing; resolved, it lies where it is named
card_file_ok() {
	local root=$1 rel=$2 p=$1/$2
	[[ ! -L ${p%/*} && ( ! -e ${p%/*} || -d ${p%/*} ) ]] || return 1
	[[ ! -L $p && ( ! -e $p || -f $p ) ]] || return 1
	[[ ! -e $p || $(realpath -e -- "$p") == "$(realpath -e -- "$root")/$rel" ]]
}

# A card that names something outside of it is refused before anything is written there
card_refuse() {
	card_umount
	die "the boot menu on the memory card is refused, nothing written: $*"
}

# card_check ROOT [ENTRY]: what this script reads and writes on the card at ROOT stays on it:
# db and db/entries are real directories, and the files written through a rename are no symlinks.
# With ENTRY (the entry of an Arch on the card): its file in db/entries, its kernel (the "linux"
# line, DIR/FILE of plain names) and its fallback "<ENTRY>-kernel-previous" as well. The entry's
# other lines (initrd, dtb, logo) are only copied into the fallback entry, never opened here.
card_check() {
	local root=$1 entry=${2:-} f rel
	for f in db db/entries; do
		[[ -d $root/$f && ! -L $root/$f ]] || card_refuse "$f is no directory"
	done
	card_file_ok "$root" db/last_index.new || card_refuse "db/last_index.new is no plain file"
	card_file_ok "$root" "db/$previous.conf.new" || card_refuse "db/$previous.conf.new is no plain file"
	[[ -n $entry ]] || return 0
	entry_name_ok "$entry" || card_refuse "the entry name '$entry' is no plain name"
	f=$root/db/entries/$entry.conf
	[[ -f $f && ! -L $f ]] || card_refuse "db/entries/$entry.conf is no plain file"
	rel=$(entry_field "$f" linux)
	card_rel_ok "$rel" || card_refuse "the kernel '$rel' of the entry $entry is not DIR/FILE on the card"
	for f in "$rel" "$rel.new" "$entry-kernel-previous/zImage" "$entry-kernel-previous/zImage.new" \
		"db/$entry-kernel-previous.conf.new"; do
		card_file_ok "$root" "$f" || card_refuse "$f of the entry $entry is no plain file on the card"
	done
}

# card_check of the card as it is mounted
card_check_mounted() {
	local root
	root=$(card_mount)
	card_check "$root"
}

# The menu numbers its entries in the order they lie in db/entries (lwext4 reads the directory
# blocks as they are); debugfs lists them the same way. Prints the index of an entry.
card_index() {
	local name=$1 i=0 e
	sync
	while read -r e; do
		[[ $e == *.conf ]] || continue
		if [[ $e == "$name.conf" ]]; then echo "$i"; return; fi
		i=$(( i + 1 ))
	done < <(debugfs -c -R 'ls -p /db/entries' "$card" 2>/dev/null | cut -d/ -f6)
	die "no entry $name on the card"
}

# The autostart: the index the menu writes when an entry is chosen, as text in 128 bytes.
# The index is read with the card unmounted (debugfs reads the device), then written.
card_autostart() {
	local name=$1 index root
	card_umount
	index=$(card_index "$name")
	root=$(card_mount)
	rm -f "$root/db/last_index.new"
	{ printf '%s' "$index"; head -c $(( 128 - ${#index} )) /dev/zero; } > "$root/db/last_index.new"
	mv "$root/db/last_index.new" "$root/db/last_index"
	card_umount
}

# Writes the entry NAME: kernel (gzip Image or boot image), the ramdisks and command line of
# the phone's vendor_boot and init_boot of the active slot, and the logo of "Arch Linux"
card_entry() {
	local root=$1 name=$2 title=$3 kernel=$4 role=$5 s dir
	s=$(slot)
	dir=$root/$name
	rm -rf "$dir.new"
	install -d -m 700 "$dir.new"
	python3 - "$kernel" "/dev/disk/by-partlabel/vendor_boot$s" "/dev/disk/by-partlabel/init_boot$s" \
		"$dir.new" <<-'EOF'
	import struct, sys
	kernel, vendor_boot, init_boot, out = sys.argv[1:5]
	align = lambda x, page: (x + page - 1) // page * page
	k = open(kernel, 'rb').read()
	if k[:8] == b'ANDROID!':
	    size, = struct.unpack_from('<I', k, 8)
	    k = k[4096:4096 + size]
	open(out + '/zImage', 'wb').write(k)
	v = open(vendor_boot, 'rb').read(64 << 20)
	if v[:8] != b'VNDRBOOT':
	    sys.exit('vendor_boot without a VNDRBOOT header')
	page, = struct.unpack_from('<I', v, 12)
	ramdisks, = struct.unpack_from('<I', v, 24)
	cmdline = v[28:28 + 2048].split(b'\0')[0].decode()
	header, dtb = struct.unpack_from('<II', v, 28 + 2048 + 4 + 16)
	start = align(header, page)
	b = open(init_boot, 'rb').read(64 << 20)
	if b[:8] != b'ANDROID!':
	    sys.exit('init_boot without an ANDROID! header')
	ksize, rsize = struct.unpack_from('<II', b, 8)
	# vendor ramdisk(s) followed by the generic ramdisk, as the bootloader concatenates them
	with open(out + '/initrd.cpio.gz', 'wb') as f:
	    f.write(v[start:start + ramdisks])
	    f.write(b[4096 + align(ksize, 4096):][:rsize])
	o = start + align(ramdisks, page)
	open(out + '/dtb.dtb', 'wb').write(v[o:o + dtb])
	open(out + '/cmdline', 'w').write(cmdline)
	EOF
	cat > "$dir.new/entry.conf" <<-EOF
	title $title
	linux $name/zImage
	initrd $name/initrd.cpio.gz
	dtb $name/dtb.dtb
	options $(cat "$dir.new/cmdline") plinius.kernel=$role
	logo real/logo.bin
	xtype UT
	xpart real
	EOF
	rm -rf "$dir"
	mv "$dir.new" "$dir"
	# A new entry file goes in through a rename from outside db/entries, in one step
	rm -f "$root/db/$name.conf.new"
	cp "$dir/entry.conf" "$root/db/$name.conf.new"
	mv "$root/db/$name.conf.new" "$root/db/entries/$name.conf"
	card_order "$root"
}

# The menu lists db/entries in the order of the directory itself, and a new file takes whatever
# slot is free. Rebuilt in a fresh directory, the entries are in the order they are copied in:
# "Arch Linux", right below it the previous kernel, then a trial (of an older version, or of
# another Arch on the card), then everything else. The autostart (db/last_index, a position) is
# moved along so it keeps naming the same entry, also one that another tool set (plinius-crypt's
# trial entry, for one).
card_order() {
	local root=$1 d=$1/db/entries new=$1/db/.entries.new f x auto="" index i=0
	local -a order=()
	# The entry the autostart names now, from the on-disk order the menu reads
	sync
	index=$(tr -d '\0' < "$root/db/last_index" 2>/dev/null || true)
	if [[ $index =~ ^[0-9]+$ ]]; then
		while read -r f; do
			[[ $f == *.conf ]] || continue
			if (( i == index )); then auto=$f; break; fi
			i=$(( i + 1 ))
		done < <(debugfs -c -R 'ls -p /db/entries' "$card" 2>/dev/null | cut -d/ -f6)
	fi
	rm -rf "$new"
	install -d -m "$(stat -c %a "$d")" -o "$(stat -c %u "$d")" -g "$(stat -c %g "$d")" "$new"
	# Copied as they are (-P): a symlink stays one, nothing is read through it
	for f in real.conf "$previous.conf" "$trial.conf"; do
		if [[ -e $d/$f || -L $d/$f ]]; then cp -pP "$d/$f" "$new/"; order+=("$f"); fi
	done
	# A card system's entry with its previous kernel and trial right below it
	for f in "$d"/*; do
		[[ ( -e $f || -L $f ) && ! -e $new/${f##*/} && ! -L $new/${f##*/} ]] || continue
		# They follow their entry (copied below when it comes)
		if [[ $f == *-kernel-trial.conf && -e ${f%-kernel-trial.conf}.conf ]] ||
			[[ $f == *-kernel-previous.conf && -e ${f%-kernel-previous.conf}.conf ]]; then
			continue
		fi
		cp -pr "$f" "$new/"
		order+=("${f##*/}")
		[[ $f == *.conf && $f != *-kernel-trial.conf && $f != *-kernel-previous.conf ]] || continue
		for x in "${f%.conf}-kernel-previous.conf" "${f%.conf}-kernel-trial.conf"; do
			if [[ -e $x || -L $x ]]; then cp -pP "$x" "$new/"; order+=("${x##*/}"); fi
		done
	done
	sync
	# One atomic swap (renameat2 RENAME_EXCHANGE): the menu never sees the directory missing
	mv --exchange -T "$new" "$d"
	rm -rf "$new"
	[[ -n $auto ]] || return 0
	i=0
	for f in "${order[@]}"; do
		[[ $f == *.conf ]] || continue
		if [[ $f == "$auto" ]]; then
			rm -f "$root/db/last_index.new"
			{ printf '%s' "$i"; head -c $(( 128 - ${#i} )) /dev/zero; } > "$root/db/last_index.new"
			mv "$root/db/last_index.new" "$root/db/last_index"
			return 0
		fi
		i=$(( i + 1 ))
	done
}

# bootcheck_accept PATH...: what this script wrote is the new reference of plinius-bootcheck
# (a boot partition, or abm-entry:NAME for a card entry with its files), so that the check at the
# next start does not report it. --written: a path this start already reported as changed stays
# for the user to confirm. Card entries are read from the device: call it with the card unmounted.
bootcheck_accept() {
	command -v plinius-bootcheck > /dev/null || return 0
	plinius-bootcheck accept --written "$@" >&2 || say "plinius-bootcheck did not take $*"
}

# changed_at_start PATH...: the check of this start reported one of PATH as changed (in the names
# of plinius-bootcheck: a partition, or abm:/FILE for a file on the boot menu card). A fallback
# copied from there is no kernel that started for sure: it is not accepted, so the alarm carries
# over to it and the user confirms it (state "unconfirmed", also for restore).
changed_at_start() {
	local out p
	command -v plinius-bootcheck > /dev/null || return 1
	# 0: unchanged or not checked yet; 2: the changed paths follow, indented
	out=$(plinius-bootcheck status 2>/dev/null) && return 1
	for p; do
		if grep -qxF -- "  $p" <<< "$out"; then return 0; fi
	done
	return 1
}

# The partitions whose ramdisks card_entry copies into the fallback entry, reported as changed
ramdisks_changed() {
	local s
	s=$(slot)
	changed_at_start "/dev/disk/by-partlabel/vendor_boot$s" "/dev/disk/by-partlabel/init_boot$s"
}

unconfirmed_note() {
	say "the fallback $1 is a copy of what plinius-bootcheck reported as changed at this start:" \
		"not accepted, the next check reports it for you to confirm"
}

# drop_trial ROOT NAME: the trial entry NAME of an older version goes; the caller orders the
# entries afterwards
drop_trial() {
	local root=$1 name=$2
	rm -f "$root/db/entries/$name.conf"
	rm -rf "${root:?}/$name"
}

# The state of a trial of an older version
drop_trial_state() {
	unset_state trial
	unset_state replace_previous
	unset_state failed
}

# --- an Arch on a memory card partition ---
entry_field() { sed -n "s/^$2 //p" "$1" | head -1; }

# The system's own entry on the card mounted at ROOT: the one whose options carry its card_word
# (not its fallback, nor the trial entry of an older version)
own_entry() {
	local root=$1 word f name
	local -a found=()
	word=$(card_word)
	for f in "$root"/db/entries/*.conf; do
		# Only plain files: nothing is read through a symlink
		[[ -f $f && ! -L $f ]] || continue
		name=${f##*/}
		name=${name%.conf}
		[[ $name == *-kernel-trial || $name == *-kernel-previous ]] && continue
		if entry_field "$f" options | tr ' ' '\n' | grep -Fqx -- "$word"; then found+=("$name"); fi
	done
	(( ${#found[@]} == 1 )) || die "no single entry for $word in the boot menu (${found[*]:-none})"
	echo "${found[0]}"
}

# The kernel file of the entry ENTRY on the card at ROOT (checked by card_check)
own_kernel() { echo "$1/$(entry_field "$1/db/entries/$2.conf" linux)"; }

# Copies a plain file to the card through a rename and reads it back. A stale temporary file goes
# first: cp would write through a symlink there.
copy_to_card() {
	[[ -f $1 && ! -L $1 ]] || die "$1 is no plain file, not copied"
	rm -f "$2.new"
	cp "$1" "$2.new"
	sync
	mv "$2.new" "$2"
	sync
	cmp -s "$1" "$2" || die "$2 on the card differs from $1 after writing"
}

# own_entry_conf ROOT ENTRY NAME TITLE OPTIONS: the entry NAME, a copy of ENTRY that starts the
# kernel NAME/zImage with OPTIONS added (plinius.kernel=<role>); ramdisk, device tree, logo and
# partitions stay ENTRY's
own_entry_conf() {
	local root=$1 entry=$2 name=$3 title=$4 extra=$5 src=$1/db/entries/$2.conf opts
	opts=$(entry_field "$src" options | sed -E 's/(^| )plinius\.kernel=[a-z]*//g')
	rm -f "$root/db/$name.conf.new"
	{
		echo "title $title"
		echo "linux $name/zImage"
		grep -vE '^(title|linux|options) ' "$src" || true
		echo "options $opts $extra"
	} > "$root/db/$name.conf.new"
	mv "$root/db/$name.conf.new" "$root/db/entries/$name.conf"
}

card_system_install() {
	local rel=$1 dir=$2 root entry kernel running installed title new="" wrote="" made=""
	local -a accept=()
	have_card || die "this Arch runs from a memory card partition, but the boot menu is missing"
	root=$(card_mount)
	entry=$(own_entry "$root")
	card_check "$root" "$entry"
	kernel=$(own_kernel "$root" "$entry")
	[[ -f $kernel ]] || die "$kernel missing"
	running=$(uname -r)
	installed=$(get installed)
	if [[ -z $installed ]]; then
		installed=$(image_release "$kernel")
		put installed "$installed"
	fi
	put entry "$entry"
	# From here on a restart must not cut the writing off: SIGTERM is ignored, also by cp and
	# debugfs (an ignored signal stays ignored across exec). A half-written card made the
	# bootloader crash on every restart.
	trap '' TERM HUP INT
	if cmp -s "$dir/Image.gz" "$kernel"; then
		say "kernel $rel is already in the boot menu entry $entry"
	else
		new=1
		# The fallback is the kernel that started for sure: the entry's while it runs, else the
		# existing fallback stays
		if [[ $running == "$installed" || ! -e $root/db/entries/$entry-kernel-previous.conf ]]; then
			title=$(entry_field "$root/db/entries/$entry.conf" title)
			install -d -m 700 "$root/$entry-kernel-previous"
			copy_to_card "$kernel" "$root/$entry-kernel-previous/zImage"
			own_entry_conf "$root" "$entry" "$entry-kernel-previous" "$title (previous kernel $installed)" \
				plinius.kernel=previous
			put previous "$installed"
			made=1
			if changed_at_start "abm:/${kernel#"$root"/}"; then
				put unconfirmed "$installed"
			else
				unset_state unconfirmed
			fi
		fi
		copy_to_card "$dir/Image.gz" "$kernel"
	fi
	put installed "$rel"
	[[ ! -e $root/db/entries/$entry-kernel-trial.conf ]] || wrote=1
	drop_trial "$root" "$entry-kernel-trial"
	drop_trial_state
	card_order "$root"
	accept=("abm-entry:$entry")
	if [[ -n $made && -n $(get unconfirmed) ]]; then
		unconfirmed_note "boot menu entry $entry-kernel-previous"
	elif [[ -e $root/db/entries/$entry-kernel-previous.conf ]]; then
		accept+=("abm-entry:$entry-kernel-previous")
	fi
	# The new kernel is the default, also after the fallback was chosen in the menu
	card_autostart "$entry"
	[[ -z $new$wrote ]] || bootcheck_accept "${accept[@]}"
	trap - TERM HUP INT
	[[ -n $new ]] || return 0
	say "kernel $rel written to the boot menu entry $entry; it starts with the next restart."
	say "Fallback: kernel $(get previous), boot menu entry $entry-kernel-previous"
}

card_system_restore() {
	local root entry kernel prev
	have_card || die "the boot menu on the memory card is missing"
	root=$(card_mount)
	entry=$(own_entry "$root")
	card_check "$root" "$entry"
	[[ -f $root/$entry-kernel-previous/zImage ]] || die "no previous kernel in the boot menu"
	kernel=$(own_kernel "$root" "$entry")
	prev=$(get previous)
	copy_to_card "$root/$entry-kernel-previous/zImage" "$kernel"
	card_umount
	if [[ -n $(get unconfirmed) ]]; then
		unconfirmed_note "kernel $prev"
	else
		bootcheck_accept "abm-entry:$entry"
	fi
	put installed "$prev"
	say "fallback $prev written to the boot menu entry $entry; it starts with the next restart"
}

# --- fallback bookkeeping ---
# Keeps the content of boot<slot> as the fallback image, with its release
save_fallback() {
	local part=$1 rel=$2
	install -d -m 700 "$state"
	[[ -e $state/boot-orig.img ]] || dump_part "$part" "$state/boot-orig.img"
	dump_part "$part" "$state/boot-previous.img"
	put previous "$rel"
	if changed_at_start "$part"; then put unconfirmed "$rel"; else unset_state unconfirmed; fi
}

# Release in boot<slot>: what we wrote there, or the original kernel read from the partition
installed_release() {
	local rel
	rel=$(get installed)
	if [[ -z $rel ]]; then
		rel=$(image_release "$(boot_part)")
		put installed "$rel"
	fi
	echo "$rel"
}

# --- commands ---
cmd_install() {
	local rel=$1 dir part running installed root="" new="" fresh="" wrote="" made=""
	local -a accept=()
	dir=$lib/$rel
	[[ -f $dir/boot.img && -f $dir/Image.gz ]] || die "no kernel $rel in $lib"
	if on_card_system; then
		card_system_install "$rel" "$dir"
		return
	fi
	part=$(boot_part)
	[[ -b $part ]] || die "$part missing"
	# A card that names something outside of it is refused before anything is written
	if have_card; then card_check_mounted; fi
	running=$(uname -r)
	installed=$(installed_release)

	# From here on a restart must not cut the writing off: SIGTERM is ignored, also by dd, cp and
	# debugfs (an ignored signal stays ignored across exec). A half-written card made the
	# bootloader crash on every restart (13.11.2026).
	trap '' TERM HUP INT
	if cmp -s -n "$(stat -c %s "$dir/boot.img")" "$dir/boot.img" "$part"; then
		say "kernel $rel is already in $part"
	else
		new=1
		# The fallback is the kernel that started for sure: the one in the partition while it
		# runs, else the existing fallback stays
		if [[ $running == "$installed" || -z $(get previous) ]]; then
			save_fallback "$part" "$installed"
			fresh=1
		fi
	fi
	# The fallback's entry in the boot menu first: cut off after it, boot<slot> still holds
	# the kernel it names
	if have_card; then
		root=$(card_mount)
		if [[ -f $state/boot-previous.img && ( -n $fresh || ! -e $root/db/entries/$previous.conf ) ]]; then
			card_entry "$root" "$previous" "Arch Linux (previous kernel $(get previous))" \
				"$state/boot-previous.img" previous
			wrote=1
			made=1
		fi
		[[ ! -e $root/db/entries/$trial.conf ]] || wrote=1
		drop_trial "$root" "$trial"
		card_order "$root"
		accept=("$part")
		if [[ -n $made ]] && { [[ -n $(get unconfirmed) ]] || ramdisks_changed; }; then
			unconfirmed_note "boot menu entry $previous"
		elif [[ -e $root/db/entries/$previous.conf ]]; then
			accept+=("abm-entry:$previous")
		fi
	fi
	drop_trial_state
	[[ -z $new ]] || write_boot "$dir/boot.img" "$part"
	put installed "$rel"
	if [[ -n $root ]]; then
		# The new kernel is the default, also after the fallback was chosen in the menu
		card_autostart real
		[[ -z $new$wrote ]] || bootcheck_accept "${accept[@]}"
	elif [[ -n $new ]]; then
		bootcheck_accept "$part"
	fi
	trap - TERM HUP INT
	[[ -n $new ]] || return 0
	say "kernel $rel written to $part; it starts with the next restart."
	say "Fallback: $(get previous) ('plinius-kernel-install restore' writes it back)"
}

# The fallback a new system brings (image/mkimage.sh): the release named as previous, kept with
# its files, gets the boot image and card entry a confirmed update leaves for its fallback. On an
# Arch from card partitions that is the entry "<entry>-kernel-previous", else boot-previous.img
# (the image inside this boot partition's AVB data, for restore) and, with the boot menu on the
# card, the entry "plinius-previous". What is there already stays.
first_fallback() {
	local prev dir root entry title part made
	prev=$(get previous)
	dir=$kept/$prev
	[[ -n $prev && -f $dir/boot.img && -f $dir/Image.gz ]] || return 0
	if on_card_system; then
		have_card || die "this Arch runs from a memory card partition, but the boot menu is missing"
		root=$(card_mount)
		entry=$(own_entry "$root")
		card_check "$root" "$entry"
		if [[ ! -e $root/db/entries/$entry-kernel-previous.conf ]]; then
			title=$(entry_field "$root/db/entries/$entry.conf" title)
			install -d -m 700 "$root/$entry-kernel-previous"
			copy_to_card "$dir/Image.gz" "$root/$entry-kernel-previous/zImage"
			own_entry_conf "$root" "$entry" "$entry-kernel-previous" "$title (previous kernel $prev)" \
				plinius.kernel=previous
			card_order "$root"
			put entry "$entry"
			made=1
		fi
		card_umount
		[[ -z ${made:-} ]] || bootcheck_accept "abm-entry:$entry-kernel-previous"
		say "fallback: kernel $prev, boot menu entry $entry-kernel-previous"
		return 0
	fi
	part=$(boot_part)
	[[ -e $part ]] || die "$part missing"
	if [[ ! -e $state/boot-previous.img ]]; then
		[[ -e $state/boot-orig.img ]] || dump_part "$part" "$state/boot-orig.img"
		python3 "$avb" "$dir/boot.img" "$part" "$state/boot-previous.img.new" "$state/boot-vbmeta.bin" ||
			die "$dir/boot.img: no fallback image for $part"
		mv "$state/boot-previous.img.new" "$state/boot-previous.img"
	fi
	if have_card; then
		root=$(card_mount)
		card_check "$root"
		made=
		if [[ ! -e $root/db/entries/$previous.conf ]]; then
			card_entry "$root" "$previous" "Arch Linux (previous kernel $prev)" \
				"$state/boot-previous.img" previous
			made=1
		fi
		card_umount
		if [[ -n $made ]] && ramdisks_changed; then
			unconfirmed_note "boot menu entry $previous"
		elif [[ -n $made ]]; then
			bootcheck_accept "abm-entry:$previous"
		fi
	fi
	say "fallback: kernel $prev ('plinius-kernel-install restore' writes it back)"
}

# The first start of a new system: the package's kernel (one release) is recorded when it runs
# already, with the image's fallback, else installed as an update would be.
# Once: afterwards a kernel is recorded as installed. Off the phone (the image's preview in QEMU:
# no boot partitions, no card system) there is nothing to set up.
first_install() {
	local f rel=""
	[[ -z $(get installed) ]] || return 0
	on_card_system || [[ -e /dev/disk/by-partlabel/boot_a || -e /dev/disk/by-partlabel/boot_b ]] ||
		return 0
	for f in "$lib"/*; do
		if [[ -f $f/boot.img ]]; then rel=${f##*/}; fi
	done
	[[ -n $rel ]] || return 0
	if [[ $(uname -r) == "$rel" ]]; then
		put installed "$rel"
		first_fallback
		return 0
	fi
	say "first start with kernel $(uname -r); setting up kernel $rel"
	cmd_install "$rel"
}

cmd_boot() {
	first_install
}

cmd_dlkm() {
	local dir
	dir=$(release_dir "$(uname -r)")
	[[ -n $dir && -f $dir/system_dlkm.img ]] || return 0
	mountpoint -q "$dlkm" && return 0
	mount --bind -o ro "$dir/system_dlkm.img" "$dlkm"
}

cmd_keep() {
	# Releases of plinius-kernel that must outlive the package files: installed, fallback, running
	local rel keepers=" $(get installed) $(get previous) $(uname -r) "
	install -d -m 700 "$kept"
	for rel in $keepers; do
		[[ -d $lib/$rel ]] || continue
		rm -rf "$kept/$rel.new"
		install -d "$kept/$rel.new"
		cp -a "$lib/$rel/." "$kept/$rel.new/"
		[[ ! -d $kmods/$rel ]] || cp -a "$kmods/$rel" "$kept/$rel.new/modules"
		rm -rf "${kept:?}/$rel"
		mv "$kept/$rel.new" "$kept/$rel"
	done
	# Nothing else needs to stay
	for rel in "$kept"/*; do
		[[ -d $rel ]] || continue
		[[ $keepers == *" ${rel##*/} "* ]] || rm -rf "$rel"
	done
}

cmd_restore() {
	local part prev
	if on_card_system; then
		card_system_restore
		return
	fi
	[[ -f $state/boot-previous.img ]] || die "no fallback kept in $state"
	part=$(boot_part)
	prev=$(get previous)
	write_part "$state/boot-previous.img" "$part"
	if [[ -n $(get unconfirmed) ]]; then
		unconfirmed_note "kernel $prev"
	else
		bootcheck_accept "$part"
	fi
	put installed "$prev"
	say "fallback $prev written to $part; it starts with the next restart"
}

cmd_status() {
	echo "running:   $(uname -r) $(role)"
	echo "installed: $(get installed)"
	echo "fallback:  $(get previous)"
	if have_card; then echo "card:      boot menu found"; else echo "card:      no boot menu"; fi
}

case ${1:-} in
hook)
	# The package holds one release; the last path wins should there ever be more
	release=
	while read -r path; do release=$(basename "$(dirname "$path")"); done
	[[ -n $release ]] || die "the hook passed no kernel"
	cmd_install "$release"
	;;
keep) cmd_keep ;;
install) cmd_install "${2:?usage: plinius-kernel-install install RELEASE}" ;;
boot) cmd_boot ;;
dlkm) cmd_dlkm ;;
restore) cmd_restore ;;
status) cmd_status ;;
*) die "usage: plinius-kernel-install hook | keep | install RELEASE | boot | dlkm | restore | status" ;;
esac
