#!/bin/sh
# Fail if the built shared object references symbols R CMD check reports:
# output to the console (stdout, stderr, printf, puts, putchar) or ending the
# process (abort, exit, _exit, and assert(), which reaches them). This covers
# the vendored Apache DataSketches headers too, which the bridge instantiates.
# Run it on an R CMD INSTALL build, which compiles with R's -DNDEBUG as CRAN
# does.
#
# Usage: tools/check-symbols [path/to/data.sketches.so]
set -eu

SO="${1:-src/data.sketches.so}"
[ -f "$SO" ] || { echo "no shared object at $SO; build the package first" >&2; exit 2; }

# Leading underscores differ by platform (_printf on macOS), and __stdoutp /
# __stderrp are macOS's names for stdout / stderr.
BAD='^_*(stdout|stderr|stdoutp|stderrp|printf|vprintf|puts|putchar|fputs|fprintf|vfprintf|abort|exit|_exit|_Exit|assert|assert_fail|assert_rtn|rand|srand)$'

found=$(nm -u "$SO" | awk '{print $NF}' | grep -E "$BAD" || true)
if [ -n "$found" ]; then
  echo "FAIL: $SO references symbols R CMD check reports:" >&2
  echo "$found" | sed 's/^/  /' >&2
  exit 1
fi
echo "==> $SO: no console-output or process-exit symbols"
