IFS=''; set -fCu  # safe mode: no split/glob = no quoting headaches
CCn='
'  # newline
let() { return $((!($1))); }

# Remove unused variable definitions from a Mamfile.
# Usage: Mamfile_rm_unused_vars <Mamfile >Mamfile.new
#
# Should work on all current POSIX compliant shells.
# By Martijn Dekker <martijn@inlv.org>, 2021, 2024. Public domain.
#
# All variables are declared with 'setv' and they are used if an expansion
# of the form ${varname} exists (the braces are mandatory in Mamfiles).

mamfile=$(let $# && cat "$1" || cat)
vars=$(printf '%s\n' $mamfile | awk '$1 == "setv" { print $2; }')
rm_unused_ere=
IFS=$CCn; for varname in $vars; do IFS=
	case $varname in
	MAMAKE_STRICT)	continue ;;
	esac
	case $mamfile in
	*"\${$varname}"* )
		;;
	* )	# add with '|' separator for Extended Regular Expression
		rm_unused_ere="${rm_unused_ere:+$rm_unused_ere|}setv[[:blank:]]+$varname([[:blank:]]|$)" ;;
	esac
done
case $rm_unused_ere in
'')	printf '%s\n' $mamfile ;;
*)	printf '%s\n' $mamfile | grep -vE $rm_unused_ere ;;
esac
