#!/usr/bin/env bash
# Boot chain for linux-cachyos-eac: CachyOS-signed systemd-boot on the ESP,
# started once through its own firmware entry (BootNext).
# Settings: /etc/eac-boot.conf (KEY=value), documented in the README.
set -euo pipefail

EAC_OPTS="lockdown=integrity lsm=landlock,lockdown,yama,integrity,bpf iommu.passthrough=0 intel_iommu=on module.sig_enforce=1 sysctl.kernel.kexec_load_disabled=1"
SDBOOT=/usr/lib/cachyos-eac/systemd-bootx64.efi.signed
CA=/usr/share/cachyos-eac/cachyos-eac-ca
LOADER_GUID=4a67b082-0a4c-41cf-b6c7-440b29bb8c4f
EFIVARS=/sys/firmware/efi/efivars

die() { echo "eac-boot: $*" >&2; exit 1; }

sbctl_conf() { sed -n "s/^$1: *//p" /etc/sbctl/sbctl.conf 2>/dev/null | head -n1; }

ESP= KERNEL_DIR= LOADER_DIR=EFI/cachyos-eac ENTRY=cachyos-eac.conf LABEL="CachyOS EAC" CMDLINE=
MODULES_DIR=$(pkg-config --variable=module_directory kmod 2>/dev/null || true)
KEYDIR=$(sbctl_conf keydir)
KEK_KEY=${KEYDIR:-/var/lib/sbctl/keys}/KEK/KEK.key
KEK_CERT=${KEYDIR:-/var/lib/sbctl/keys}/KEK/KEK.pem
OWNER_GUID=
[[ -r /etc/eac-boot.conf ]] && . /etc/eac-boot.conf
MODULES_DIR=${MODULES_DIR:-/lib/modules}
KERNEL_DIR=${KERNEL_DIR:-$(</etc/machine-id)/linux-cachyos-eac}
[[ $ENTRY =~ ^[A-Za-z0-9._-]+\.conf$ ]] || die "ENTRY must be a file name ending in .conf: $ENTRY"

esp() {
	local d
	for d in $ESP /efi /boot/efi /boot; do
		[[ $(findmnt -no FSTYPE --mountpoint "$d" 2>/dev/null) == vfat ]] && { echo "$d"; return; }
	done
	die "no mounted vfat ESP found, set ESP in /etc/eac-boot.conf"
}

kernel_dir() { echo "$(esp)/$KERNEL_DIR"; }
loader() { echo "$(esp)/$LOADER_DIR/systemd-bootx64.efi"; }

kver() {
	local k
	k=$(ls -d "$MODULES_DIR"/*-cachyos-eac 2>/dev/null | sort -V | tail -n1) || true
	[[ -f $k/vmlinuz ]] || die "no linux-cachyos-eac kernel in $MODULES_DIR"
	echo "${k##*/}"
}

# Base command line (CMDLINE, /etc/kernel/cmdline or the running system), plus the EAC options.
cmdline() {
	local base=$CMDLINE opt out=()
	if [[ -z $base ]]; then
		if [[ -f /etc/kernel/cmdline ]]; then base=$(</etc/kernel/cmdline); else base=$(</proc/cmdline); fi
	fi
	for opt in $base; do
		case $opt in BOOT_IMAGE=*|initrd=*) continue ;; esac
		[[ " $EAC_OPTS " == *" $opt "* ]] && continue
		out+=("$opt")
	done
	echo "${out[*]} $EAC_OPTS"
}

bootnum() {
	efibootmgr | sed -n "s/^Boot\([0-9A-F]\{4\}\)\*\{0,1\} $LABEL\t.*/\1/p" | head -n1
}

update() {
	local esp kv dir conf
	esp=$(esp)
	kv=$(kver)
	dir=$esp/$KERNEL_DIR
	mkdir -p "$dir" "$esp/$LOADER_DIR" "$esp/loader/entries"

	dracut --force --hostonly --kver "$kv" "$dir/initramfs.new"
	install -m644 "$MODULES_DIR/$kv/vmlinuz" "$dir/vmlinuz.new"
	mv -f "$dir/initramfs.new" "$dir/initramfs"
	mv -f "$dir/vmlinuz.new" "$dir/vmlinuz"
	install -m644 "$SDBOOT" "$esp/$LOADER_DIR/systemd-bootx64.efi"

	printf 'title   CachyOS (EAC)\nlinux   /%s/vmlinuz\ninitrd  /%s/initramfs\noptions %s\n' \
		"$KERNEL_DIR" "$KERNEL_DIR" "$(cmdline)" > "$esp/loader/entries/$ENTRY"

	# loader.conf is shared by every systemd-boot on this ESP: only write our own.
	conf=$(printf 'default %s\ntimeout 0\n' "$ENTRY")
	if [[ ! -e $esp/loader/loader.conf || $(<"$esp/loader/loader.conf") == "$conf" ]]; then
		printf '%s\n' "$conf" > "$esp/loader/loader.conf"
	else
		echo "eac-boot: kept the existing $esp/loader/loader.conf; eac-boot boot selects $ENTRY once"
	fi
	echo "eac-boot: $kv installed to $dir"
}

# Same file contents as a certificate in a signature database variable?
in_sigdb() {
	local var=$1 der=$2 f
	efi-readvar -v "$var" -o "$tmp/$var.esl" >/dev/null
	(cd "$tmp" && sig-list-to-certs "$var.esl" "$var" >/dev/null 2>&1) || true
	for f in "$tmp/$var"-*.der; do
		[[ -f $f ]] && cmp -s "$f" "$der" && return 0
	done
	return 1
}

# Appends only the CachyOS EAC CA. Every other db entry stays, and nothing is added twice.
enroll() {
	tmp=$(mktemp -d)
	trap 'rm -rf "$tmp"' EXIT
	if in_sigdb db "$CA.der"; then
		echo "eac-boot: the CachyOS EAC CA is already in db, nothing to do"
		return
	fi
	[[ -r $KEK_KEY && -r $KEK_CERT ]] || die "KEK key or certificate not found ($KEK_KEY, $KEK_CERT); set KEK_KEY and KEK_CERT in /etc/eac-boot.conf"
	openssl x509 -in "$KEK_CERT" -outform DER -out "$tmp/kek.der"
	in_sigdb KEK "$tmp/kek.der" || die "$KEK_CERT is not enrolled in KEK, so the firmware would reject the update"
	local guid=${OWNER_GUID:-$(cat "$(sbctl_conf guid)" 2>/dev/null || cat /proc/sys/kernel/random/uuid)}
	cert-to-efi-sig-list -g "$guid" "$CA.crt" "$tmp/ca.esl" >/dev/null
	sign-efi-sig-list -a -g "$guid" -c "$KEK_CERT" -k "$KEK_KEY" db "$tmp/ca.esl" "$tmp/ca.auth" >/dev/null
	chattr -i "$EFIVARS/db-d719b2cb-3d3a-4596-a3bc-dad00e67656f" 2>/dev/null || true
	efi-updatevar -a -f "$tmp/ca.auth" db
	in_sigdb db "$CA.der" || die "the firmware did not take the CachyOS EAC CA"
	echo "eac-boot: appended the CachyOS EAC CA to db; existing entries were kept"
}

# With a boot number, the entry is created there and replaces the entry that has it.
setup() {
	local want=${1^^} have
	[[ -z $want || $want =~ ^[0-9A-F]{4}$ ]] || die "boot number must be 4 hex digits: $1"
	update
	have=$(bootnum)
	if [[ -n $have && ( -z $want || $have == "$want" ) ]]; then
		echo "eac-boot: firmware entry Boot$have \"$LABEL\" exists"
	else
		create "$have" "$want"
	fi
	bootorder_last
}

# Firmware boot menus only list BootOrder entries; at the end it never boots by default.
bootorder_last() {
	local n order
	n=$(bootnum)
	order=$(efibootmgr | sed -n 's/^BootOrder: //p')
	[[ ,$order, == *,$n,* ]] && return
	efibootmgr --bootorder "${order:+$order,}$n" >/dev/null
	echo "eac-boot: added Boot$n to the end of BootOrder"
}

create() {
	local have=$1 want=$2 old esp src
	[[ -n $have ]] && efibootmgr -b "$have" -B >/dev/null
	if [[ -n $want ]]; then
		old=$(efibootmgr | sed -n "s/^Boot$want\*\{0,1\} \([^\t]*\).*/\1/p")
		if [[ -n $old ]]; then
			efibootmgr -b "$want" -B >/dev/null
			echo "eac-boot: removed Boot$want \"$old\""
		fi
	fi
	esp=$(esp)
	src=$(findmnt -no SOURCE --mountpoint "$esp")
	efibootmgr --create-only ${want:+--bootnum "$want"} --disk "/dev/$(lsblk -no PKNAME "$src")" \
		--part "$(<"/sys/class/block/${src##*/}/partition")" \
		--label "$LABEL" --loader "\\${LOADER_DIR//\//\\}\\systemd-bootx64.efi" >/dev/null
	echo "eac-boot: created firmware entry Boot$(bootnum) \"$LABEL\""
}

# systemd-boot reads LoaderEntryOneShot (UTF-16LE, NUL-terminated) and deletes it.
oneshot() {
	local var=$EFIVARS/LoaderEntryOneShot-$LOADER_GUID tmp i data='\x07\x00\x00\x00'
	for ((i = 0; i < ${#ENTRY}; i++)); do data+="${ENTRY:i:1}\\x00"; done
	tmp=$(mktemp)
	printf "$data"'\x00\x00' > "$tmp"
	[[ -e $var ]] && chattr -i "$var" 2>/dev/null
	cat "$tmp" > "$var"
	rm -f "$tmp"
}

boot() {
	local n
	n=$(bootnum)
	[[ -n $n ]] || die "no \"$LABEL\" firmware entry, run: eac-boot setup"
	oneshot
	efibootmgr --bootnext "$n" >/dev/null
	reboot
}

case ${1:-} in
	esp|cmdline|loader) "$1"; exit ;;
	kernel-dir) kernel_dir; exit ;;
esac
[[ $(id -u) == 0 ]] || die "run as root"
case ${1:-} in
	enroll|update|boot|oneshot) "$1" ;;
	setup) setup "${2:-}" ;;
	*) echo "usage: eac-boot {enroll|setup [bootnum]|update|boot|cmdline|esp|kernel-dir|loader}" >&2; exit 2 ;;
esac
