#!/bin/sh
# Ruhiger Start (bashclub-base): ergänzt org.zfsbootmenu:commandline des
# Boot-Pools (<pool>/ROOT und jedes BE mit eigenem Wert) um die Parameter
# des ruhigen Starts. Vorhandenes bleibt, auch ein eigener Wert desselben
# Parameters (loglevel=7 bleibt, nosplash verhindert splash). Danach steht
# org.bashclub:quiet-boot=1 auf <pool>/ROOT, und es ergänzt nie wieder: Wer
# Parameter entfernt, behält das. --force ergänzt trotzdem.
#   /usr/lib/bashclub/quiet-boot [--force]
set -eu
PARAMS="quiet splash loglevel=3 vt.global_cursor_default=0"
VERSION=1
command -v zfs >/dev/null 2>&1 || exit 0
pool=$(zpool list -H -o name,bootfs 2>/dev/null | awk '$2 != "-" {print $1; exit}')
[ -n "$pool" ] || exit 0
root=$pool/ROOT
zfs list -H -o name "$root" >/dev/null 2>&1 || exit 0
done=$(zfs get -H -o value org.bashclub:quiet-boot "$root")
case $done in
[0-9]*) [ "$done" -lt "$VERSION" ] || [ "${1:-}" = --force ] || exit 0 ;;
esac
merge() {
	line=$1
	for p in $PARAMS; do
		key=${p%%=*}
		found=no
		for t in $line; do
			case $t in "$key" | "$key"=* | "no$key") found=yes ;; esac
		done
		[ "$found" = yes ] || line="${line:+$line }$p"
	done
	printf '%s
' "$line"
}
if ! zfs get -H -r -t filesystem -s local -o name org.zfsbootmenu:commandline "$root" | grep -q .; then
	zfs set org.zfsbootmenu:commandline="$PARAMS" "$root"
	echo "quiet-boot: $root: $PARAMS"
fi
zfs get -H -r -t filesystem -s local -o name,value org.zfsbootmenu:commandline "$root" |
	while IFS="$(printf '	')" read -r ds value; do
		new=$(merge "$value")
		[ "$new" = "$value" ] && continue
		zfs set org.zfsbootmenu:commandline="$new" "$ds"
		echo "quiet-boot: $ds: $new"
	done
zfs set org.bashclub:quiet-boot="$VERSION" "$root"
