#!/bin/sh
# The amalgamation's rule (docs/dev/amalgamation.md): pic's sources must merge into one
# translation unit. Fails when
#   - a src/*.c or src/tui/*.c is missing from the list in the Makefile (PIC_SRC, passed as args);
#   - two files define the same static function or variable, typedef, struct, union or enum tag,
#     or enumerator (a file-local macro is no collision: the generator undefines it at the end of
#     its file);
# That the merged pic.c compiles under the full warning flags (which catches a local that shadows
# another file's static) is `make pic` and `make pic-dev` themselves: they build that unit.
# Usage: sh test/pic/amalgam.sh FILE.c...
set -eu
cd "$(dirname "$0")/../.."

[ $# -gt 0 ] || { echo "usage: amalgam.sh FILE.c..." >&2; exit 2; }
rc=0

for f in src/*.c src/tui/*.c; do
	case " $* " in *" $f "*) ;; *) echo "amalgam: $f is not in PIC_SRC, so it is not in pic.c"; rc=1 ;; esac
done

dups=$(awk -f test/pic/amalgam-names.awk "$@" |
	awk '{ n[$1]++; w[$1] = w[$1] " " $3 " (" $2 ")" } END { for (k in n) if (n[k] > 1) print k ":" w[k] }' | sort)
if [ -n "$dups" ]; then
	echo "amalgam: defined in more than one file (rename with the file's prefix, see docs/dev/amalgamation.md):"
	echo "$dups" | sed 's/^/  /'
	rc=1
fi

[ "$rc" = 0 ] && echo "amalgam: ok"
exit "$rc"
