#!/bin/bash
# deploy 完整性自检:
#   收集 webrtcpush + deploy/lib/*.so 的全部 NEEDED 依赖,
#   每个都必须能在 deploy/lib 或设备系统库(白名单)中找到, 缺了报错退出。
# 用法: bash scripts/check_deps.sh [deploy目录]   (deploy 目标自动调用)
set -u
HERE="$(cd "$(dirname "$0")/.." && pwd)"
DEPLOY="${1:-$HERE/build/deploy}"
RE="$HOME/rv1106sdk/luckfox-pico/tools/linux/toolchain/arm-rockchip830-linux-uclibcgnueabihf/bin/arm-rockchip830-linux-uclibcgnueabihf-readelf"
[ -x "$RE" ] || RE=readelf

if [ ! -s "$DEPLOY/lib/ca-certificates.crt" ]; then
  echo "  [MISS] ca-certificates.crt  <-- TLS CA bundle missing"
  exit 1
fi

# 设备 (luckfox Buildroot/uClibc 固件) 自带的运行时库, 不打包
SYS_WHITELIST="libc.so.0 ld-uClibc.so.1 libstdc++.so.6 libgcc_s.so.1 \
libm.so.6 libm.so.0 libdl.so.0 librt.so.0 libpthread.so.0"

needed_of(){   # 打印一个 ELF 的所有 NEEDED
  "$RE" -d "$1" 2>/dev/null | grep NEEDED | sed 's/.*\[\(.*\)\]/\1/' | sort -u
}

# 1) 汇总闭包
ALL_NEEDED=$( { needed_of "$DEPLOY/webrtcpush"; \
                needed_of "$DEPLOY/webrtcpush-core"; \
                for f in "$DEPLOY"/lib/*.so; do needed_of "$f"; done; } | sort -u)

# 2) 逐项检查
MISSING=0
while IFS= read -r lib; do
  [ -z "$lib" ] && continue
  # deploy/lib 里有 (文件名或 soname 链) ?
  if ls "$DEPLOY/lib/$lib" >/dev/null 2>&1; then continue; fi
  # 设备系统自带 ?
  if echo " $SYS_WHITELIST " | grep -q " $lib "; then
    echo "  [sys]  $lib (设备系统自带, 不打包)"
    continue
  fi
  echo "  [MISS] $lib  <-- deploy/lib 缺失! 请补进 CMakeLists deploy 目标"
  MISSING=$((MISSING+1))
done <<< "$ALL_NEEDED"

echo "----------------------------------------"
if [ "$MISSING" -gt 0 ]; then
  echo "check_deps: FAIL ($MISSING 个缺失)"
  exit 1
fi
echo "check_deps: OK (闭包完整)"
