#!/bin/sh
# verify_silero_exports.sh
#
# Asserts that all six chanora_silero_vad_* C symbols that the Rust
# chanora_bridge framework resolves via dlsym(RTLD_DEFAULT) are present
# in the linked app binary's dynamic export table — verified per
# architecture slice for macOS universal builds, because `nm` on a
# universal Mach-O without -arch will succeed if a symbol exists in ANY
# slice, not every slice. A missing symbol in just the x86_64 slice
# would silently break Intel Macs.
#
# Without this check, Xcode Archive's -dead_strip can remove these
# Swift @_cdecl symbols (no Swift caller exists) and CoreML VAD falls
# back to WebRTC on TestFlight/App Store with no compile-time,
# link-time, or runtime warning. We hit that bug once; this script
# ensures we never ship it again.
#
# Runs as an Xcode build phase after Link Binary, on iOS and macOS.

set -e

if [ -z "${TARGET_BUILD_DIR}" ] || [ -z "${EXECUTABLE_PATH}" ]; then
    echo "error: verify_silero_exports.sh requires TARGET_BUILD_DIR and EXECUTABLE_PATH (run from Xcode build phase)" >&2
    exit 1
fi

BINARY="${TARGET_BUILD_DIR}/${EXECUTABLE_PATH}"

if [ ! -f "${BINARY}" ]; then
    echo "error: app binary not found at ${BINARY}" >&2
    exit 1
fi

REQUIRED_SYMBOLS="
_chanora_silero_vad_create
_chanora_silero_vad_destroy
_chanora_silero_vad_reset
_chanora_silero_vad_process
_chanora_silero_vad_last_error
_chanora_silero_vad_free_string
"

# Enumerate slices. `lipo -archs` prints arches space-separated for
# universal Mach-O; for thin binaries it prints the single arch.
ARCHS=$(xcrun lipo -archs "${BINARY}" 2>/dev/null || echo "")
if [ -z "${ARCHS}" ]; then
    echo "error: xcrun lipo -archs failed for ${BINARY}; cannot enumerate slices" >&2
    exit 1
fi

FAILED=0
for arch in ${ARCHS}; do
    EXPORTED=$(xcrun nm -arch "${arch}" -gU "${BINARY}" 2>/dev/null | awk '{print $NF}')
    if [ -z "${EXPORTED}" ]; then
        echo "error: xcrun nm produced no output for arch=${arch} on ${BINARY}" >&2
        FAILED=1
        continue
    fi

    MISSING=""
    for sym in ${REQUIRED_SYMBOLS}; do
        if ! echo "${EXPORTED}" | grep -qx "${sym}"; then
            MISSING="${MISSING} ${sym}"
        fi
    done

    if [ -n "${MISSING}" ]; then
        echo "error: chanora_silero_vad exports missing from $(basename "${BINARY}") [arch=${arch}]:${MISSING}" >&2
        FAILED=1
    fi
done

if [ "${FAILED}" -ne 0 ]; then
    echo "error: Rust dlsym(RTLD_DEFAULT) resolution will fail and CoreML VAD will fall back to WebRTC." >&2
    echo "error: Check OTHER_LDFLAGS -exported_symbol entries in Flutter/*.xcconfig and the @_cdecl exports in Runner/SileroCoreMLBridge.swift." >&2
    exit 1
fi

echo "verify_silero_exports: all 6 chanora_silero_vad_* symbols present in $(basename "${BINARY}") [arches: ${ARCHS}]"
