#!/bin/sh

echo "/* autogenerated list of to be exported functions from lua */"

HEADERS=
OBJECTS=

# split argument list into headers (*.h) and objects (*.o)
for F; do
	case $F in
	*.h)
		HEADERS="$HEADERS $F"
		;;
	*.o)
		OBJECTS="$OBJECTS $F"
		;;
	esac
done

is_compiled_symbol() {
	S=$1

	for O in $OBJECTS; do
		if nm $O | grep -q -w $S; then
			return 0
		fi
	done
	return 1
}

get_exports_from_header() {
	H=$1

	grep -e '\(LUA_API\|LUALIB_API\)' $H |
		sed 's/([^(]*$//' |
		sed 's/[()*]//g' |
		awk '{print $NF}' |
		sort
}

for H in $HEADERS; do
	# extract tail path component
	HTAIL=${H##*/}

	# skip luaconf.h
	if [ "$HTAIL" = "luaconf.h" ]; then continue; fi

	HEADER_WRITTEN=no

	get_exports_from_header $H |
		while read S; do
			# skip symbols not visible in any object binary
			if ! is_compiled_symbol $S; then continue; fi

			# write header include only if at least one symbol found
			if [ $HEADER_WRITTEN = no ]; then
				echo
				echo "#include \"$HTAIL\""

				HEADER_WRITTEN=yes
			fi

			echo "EXPORT_SYMBOL($S);"
		done
done
