#!/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).
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"
LABEL="CachyOS EAC"
SDBOOT=/usr/lib/cachyos-eac/systemd-bootx64.efi.signed

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

esp() {
	local d
	for d in ${EAC_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 EAC_ESP"
}

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

# Base command line from /etc/kernel/cmdline or the running system, plus the EAC options.
cmdline() {
	local src=/proc/cmdline opt out=()
	[[ -f /etc/kernel/cmdline ]] && src=/etc/kernel/cmdline
	for opt in $(<"$src"); 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 mid dir
	esp=$(esp)
	kv=$(kver)
	mid=$(</etc/machine-id)
	dir=$esp/$mid/linux-cachyos-eac
	mkdir -p "$dir" "$esp/EFI/cachyos-eac" "$esp/loader/entries"

	dracut --force --hostonly --kver "$kv" "$dir/initramfs.new"
	install -m644 "/lib/modules/$kv/vmlinuz" "$dir/vmlinuz.new"
	mv -f "$dir/initramfs.new" "$dir/initramfs"
	mv -f "$dir/vmlinuz.new" "$dir/vmlinuz"
	install -m644 "$SDBOOT" "$esp/EFI/cachyos-eac/systemd-bootx64.efi"

	printf 'title   CachyOS (EAC)\nlinux   /%s/linux-cachyos-eac/vmlinuz\ninitrd  /%s/linux-cachyos-eac/initramfs\noptions %s\n' \
		"$mid" "$mid" "$(cmdline)" > "$esp/loader/entries/cachyos-eac.conf"
	printf 'default cachyos-eac.conf\ntimeout 0\n' > "$esp/loader/loader.conf"
	echo "eac-boot: $kv installed to $dir"
}

# The whole db is rewritten: sbctl --append adds every key again, and firmware keeps duplicates.
enroll() {
	sbctl enroll-keys --partial db --microsoft --custom --ignore-immutable
}

# 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\} \([^	]*\).*/\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 '\EFI\cachyos-eac\systemd-bootx64.efi' >/dev/null
	echo "eac-boot: created firmware entry Boot$(bootnum) \"$LABEL\""
}

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

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