#! /bin/sh

set -eu

rm -f tmp.*

symbol_list () {
    nm "$1" | sed -n '/ [DRT] /s/.* //p' | sort
}

undef_list () {
    nm "$1" | sed -n '/ U /s/.* //p' | sort
}

if [ -f "../lib/libsigsum.a" ] ; then
   # Prefix '__' reserved (and commonly used) by compiler, see ANSI-C 7.3.1.
   # Ignore compiler internal symbols, e.g., __x86.get_pc_thunk.bx
   if symbol_list "../lib/libsigsum.a" | grep -E -v '^(_?sigsum_|__)' > tmp.static-symbols
   then
       echo >&2 "Exported symbols in libsigsum.a, lacking the sigsum prefix:"
       cat >&2 tmp.static-symbols
       exit 1
   fi
fi

if [ -f "../lib/libsigsum.so" ] ; then
   if symbol_list "../lib/libsigsum.so" | grep -E -v '^_?sigsum_' > tmp.shared-symbols
   then
       echo >&2 "Exported symbols in libsigsum.so, lacking the sigsum prefix:"
       cat >&2 tmp.shared-symbols
       exit 1
   fi
   if [ -f "../tools/sigsum-c-verify" ] ; then
       # Check that there are no references to internal symbols.
       if undef_list "../tools/sigsum-c-verify" | grep @SIGSUM_INTERNAL > tmp.internal-symbols ; then
	   echo >&2 "Internal symbols referenced by sigsum-c-verify:"
	   cat tmp.internal-symbols
	   exit 1
       fi
   fi
fi
