#!/bin/sh
# Guard (RFC 005 §2.5): check a final kernel .config against required-config.txt.
# Usage: check-required-config.sh <.config> [release|debug]
# libkrunfw's scripts/check-required-config.sh pattern ("EXACT_CONFIG_LINE|why"), extended with
# negative lines ("# CONFIG_X is not set|why": X must not be set to anything) and per-variant
# lines ("release:" / "debug:" prefix).
set -u
cfg=${1:?usage: $0 <.config> [release|debug]}
variant=${2:-release}
req="$(dirname "$0")/required-config.txt"
[ -f "$cfg" ] || { echo "  FAIL  $cfg: file not found"; exit 1; }
fail=0 n=0
while IFS= read -r entry; do
	case $entry in '' | '#'[!\ ]* | '# '[!C]* | '#') continue ;; esac
	case $entry in
		release:*) [ "$variant" = release ] || continue; entry=${entry#release:} ;;
		debug:*) [ "$variant" = debug ] || continue; entry=${entry#debug:} ;;
	esac
	line=${entry%%|*}
	why=${entry#*|}
	n=$((n + 1))
	case $line in
		'# CONFIG_'*' is not set')
			sym=${line#\# }; sym=${sym%% *}
			if grep -q "^$sym=" "$cfg"; then
				echo "  FAIL  $(grep "^$sym=" "$cfg") — must be off: $why"; fail=1
			else
				echo "  ok    $line"
			fi ;;
		CONFIG_*)
			if grep -qxF "$line" "$cfg"; then
				echo "  ok    $line"
			else
				sym=${line%%=*}
				got=$(grep -E "^($sym=|# $sym is not set)" "$cfg" || echo "absent")
				echo "  FAIL  want '$line', got '$got' — $why"; fail=1
			fi ;;
		*) echo "  FAIL  malformed line in required-config.txt: $entry"; fail=1 ;;
	esac
done < "$req"
if [ "$fail" -ne 0 ]; then
	echo "Required kernel config ($variant) not met in $cfg (see above)." >&2
	exit 1
fi
echo "All $n required kernel config lines ($variant) hold in $cfg."
