#!/bin/sh
# filter stdin or file for words related to
# the specified target architecture
#
# args: [-a arch] [-i file]

if [ "$1" = "-a" -a -n "$2" ]; then
	a="$2"
	shift 2
else
	cat
	exit
fi

if [ "$1" = "-i" -a -w "$2" ]; then
	f="$2"
	t="`mktemp`"
fi

# map meta-arches for prefiltering
# NB: biarch gets special expansion later
case "$a" in
i586)
	A="(IA32|X86)";;
x86_64)
	A="X86";;
e2k*)
	A="E2K";;
aarch64|arm*)
	A="ARM";;
*)
	A=;;
esac

# NB: pipe runs in parallel => faster than -e -e
cat ${f:+"$f"} |
sed -r  ':loop; s/^((([^@]+@!)[^,]+)+),([a-zA-Z0-9_]+)/\1@!\4/; t loop' |
sed -r  ':loop; s/^((([^@]+@)[^,]+)+),([a-zA-Z0-9_]+)/\1\n\3\4/; t loop' |
sed -rn "s/\<([^@ ]*)\>|\<([^@ ]*)@$A\>[^ ]*\>/\1\2/pg" |
sed -rn "s/\<([^@ ]*)\>|\<[^ ]*@\!$A\>[^ ]*\> */\1/pg" |
sed -r  "s/\<([^@ ]*)@IA32\>/\1@i586 i586-\1@x86_64/g" |
sed -rn "s/\<([^@ ]*)\>|\<([^@ ]*)@$a\>[^ ]*\>/\1\2/pg" |
sed -rn "s/\<([^@ ]*)\>|\<[^ ]*@\!$a\>[^ ]*\> */\1/pg" |
sed -r  "s/\<([^@ ]*)@\![^ ]+\>/\1/g" |
sed -r  "s/\<([^@ ]*)@[^@ ]+\> *//g" |
sed -r  "s/^ +//;s/ +$//;/^$/d" |
if [ -n "$f" ]; then
	cat > "$t" && mv "$t" "$f"
else
	cat
fi

# stick this for debugging sed pipeline and run the script
# with >/dev/null to see what flows in a particular place:
#   tee /dev/stderr |