#! /bin/sh

# Build a list of internal function and variable prototypes.
t=__wt.$$
trap 'rm -f $t' 0 1 2 3 13 15

# proto --
#	extract public functions.
proto()
{
	sed -n \
	    -e '/^__wt_[a-z]/!{' \
		-e h \
		-e d \
	    -e '}' \
	    -e x \
	    -e '/^static/d' \
	    -e x \
	    -e ': loop' \
	    -e H \
	    -e n \
	    -e '/;/b end' \
	    -e '/^{/!b loop' \
	    -e ': end' \
	    -e x \
	    -e 's/ =.*$//' \
	    -e '/#/!s/\n/ /g' \
	    -e '# line cleanup, strip out random whitespace' \
	    -e 's/  */ /g' \
	    -e 's/\* /\*/g' \
	    -e 's/( /(/' \
	    -e 's/^/extern /' \
	    -e 's/WT_GCC_FUNC_ATTRIBUTE/WT_GCC_FUNC_DECL_ATTRIBUTE/g' \
	    -e '# If a line ends in #endif, appending a semicolon will result' \
	    -e '# in an illegal expression, force an appended newline using' \
	    -e '# the H command because substitute may not allow newline in' \
	    -e '# the RHS of the expression.' \
	    -e '/#endif$/{' \
		-e x \
		-e 's/.*//' \
		-e H \
		-e x \
	    -e '}' \
	    -e '# Add the warn_unused_result attribute to any external' \
	    -e '# functions that return a boolean or an int.' \
	    -e '/^extern bool /s/$/ WT_GCC_FUNC_DECL_ATTRIBUTE((warn_unused_result))/' \
	    -e '/^extern int /s/$/ WT_GCC_FUNC_DECL_ATTRIBUTE((warn_unused_result))/' \
	    -e 's/$/;/' \
	    -e p < $1
}

# externs --
#	generate the list of prototypes given a file list
externs()
{
(cat <<EOF
/* DO NOT EDIT: automatically built by dist/s_prototypes. */

EOF
	for i in $l; do
		proto ../$i
	done) > $t
	./s_clang-format "${PWD}/$t"
	cmp $t $f > /dev/null 2>&1 ||
	    (echo "Building $f" && rm -f $f && cp $t $f)
}

f=../src/include/extern_win.h
l=`sed \
    -e '/os_win/!d' \
    -e 's/[ ].*$//' filelist`
externs

f=../src/include/extern_posix.h
l=`sed \
    -e '/os_posix/!d' \
    -e 's/[ ].*$//' filelist`
externs

f=../src/include/extern.h
l=`sed \
    -e '/^[a-z]/!d' \
    -e '/\/checksum\/arm64/d' \
    -e '/\/checksum\/power8/d' \
    -e '/\/checksum\/zseries/d' \
    -e '/os_posix/d' \
    -e '/os_win/d' \
    -e 's/[ ].*$//' filelist`
externs

exit 0
