#!/system/bin/sh
# UVC + Camera2 故障采集（Open Camera ID:1、抖音扫脸、左右镜像）
# Usage:
#   adb shell uvc-troubleshoot              # 完整报告（默认）
#   adb shell uvc-troubleshoot log          # 清空 logcat 并提示复现后执行 logcat
#   adb shell uvc-troubleshoot log pull     # 导出最近 UVC/Camera2 相关 log 摘要
#
# 未刷入 vendor 包时可临时：
#   adb push uvc-troubleshoot.sh /data/local/tmp/
#   adb shell sh /data/local/tmp/uvc-troubleshoot.sh

set -u

OUT="/data/local/tmp/uvc-troubleshoot-$(date +%Y%m%d-%H%M%S).txt"
CMD="${1:-report}"
ARG2="${2:-}"

log() {
  # shellcheck disable=SC2039
  printf '%s\n' "$*" | tee -a "$OUT"
}

section() {
  log ""
  log "========== $* =========="
}

warn() {
  log "[WARN] $*"
}

ok() {
  log "[OK] $*"
}

fail() {
  log "[FAIL] $*"
}

prop() {
  getprop "$1" 2>/dev/null || echo ""
}

# --- log pull (after reproduce) ---
if [ "$CMD" = "log" ] && [ "$ARG2" = "pull" ]; then
  OUT="/data/local/tmp/uvc-troubleshoot-logcat-$(date +%Y%m%d-%H%M%S).txt"
  logcat -d -s UvcReplacePolicy:* CameraService:* Camera2ClientBase:* CameraDeviceClient:* \
    ExtCamDevSsn@3.4:* ExtCamDev@3.4:* CameraProviderManager:* AndroidRuntime:E \
    2>/dev/null >"$OUT"
  echo "Saved: $OUT"
  echo "Pull: adb pull $OUT"
  exit 0
fi

# --- log clear + instruct ---
if [ "$CMD" = "log" ]; then
  logcat -c 2>/dev/null
  echo "logcat cleared. Reproduce: Open Camera API2 front (ID:1) OR Douyin face scan, wait 10s."
  echo "Then: adb shell uvc-troubleshoot log pull"
  echo "Or PC: collect-uvc-camera2-troubleshoot.bat"
  exit 0
fi

: >"$OUT" 2>/dev/null || OUT="/data/local/tmp/uvc-troubleshoot-latest.txt"

section "UVC troubleshoot kebab"
log "time=$(date)"
log "script=uvc-troubleshoot expect_build=kebab-p1-uvc-c2fix-cn-20261014 (Settings 直播选项 BUILD_ID)"

section "1. 系统 / ROM 线索"
log "ro.build.display.id=$(prop ro.build.display.id)"
log "ro.lineage.version=$(prop ro.lineage.version)"
log "ro.vendor.build.date=$(prop ro.vendor.build.date)"
log "cameraserver=$(pidof cameraserver 2>/dev/null || echo missing)"
log "vendor.camera.provider external=$(pidof android.hardware.camera.provider@2.7-external-service 2>/dev/null || echo missing)"

section "2. 无界 UVC 策略属性"
log "note: adb shell setprop persist.vendor.camera.uvc.* 会失败(SELinux)；请用 设置->直播选项->应用 或 adb root + uvc-replace-role"
for p in \
  ro.vendor.camera.uvc.enabled \
  ro.vendor.camera.uvc.replace_role \
  ro.vendor.camera.uvc.rotation \
  ro.vendor.camera.uvc.mirror_horizontal \
  ro.vendor.camera.uvc.enabled \
  ro.vendor.camera.uvc.replace_role \
  ro.vendor.camera.uvc.rotation \
  persist.vendor.camera.uvc.enabled \
  persist.vendor.camera.uvc.replace_role \
  persist.vendor.camera.uvc.rotation \
  persist.vendor.camera.uvc.mirror_horizontal \
  persist.vendor.camera.uvc.debug \
  persist.vendor.camera.uvc.fallback_reason \
  vendor.camera.uvc.enabled \
  vendor.camera.uvc.replace_role \
  vendor.camera.uvc.rotation \
  vendor.camera.uvc.mirror_horizontal \
  vendor.camera.uvc.match \
  vendor.camera.uvc.lens_facing_override; do
  log "$p=$(prop "$p")"
done

ENABLED="$(prop persist.vendor.camera.uvc.enabled)"
[ -z "$ENABLED" ] && ENABLED="$(prop vendor.camera.uvc.enabled)"
[ -z "$ENABLED" ] && ENABLED="$(prop ro.vendor.camera.uvc.enabled)"
ROLE="$(prop persist.vendor.camera.uvc.replace_role)"
[ -z "$ROLE" ] && ROLE="$(prop vendor.camera.uvc.replace_role)"
[ -z "$ROLE" ] && ROLE="$(prop ro.vendor.camera.uvc.replace_role)"
MIRROR_P="$(prop persist.vendor.camera.uvc.mirror_horizontal)"
MIRROR_V="$(prop vendor.camera.uvc.mirror_horizontal)"

if [ "$MIRROR_P" = "1" ] && [ "$MIRROR_V" != "1" ]; then
  warn "persist 镜像=1 但 vendor.camera.uvc.mirror_horizontal 未同步 → init.uvc-camera.rc 或需重启 / 点「应用」"
fi
if [ "$MIRROR_P" != "1" ] && [ "$MIRROR_V" = "1" ]; then
  warn "vendor 镜像=1 但 persist 未写 → 设置里开关后需点「应用」"
fi
FALLBACK="$(prop persist.vendor.camera.uvc.fallback_reason)"
if [ -n "$FALLBACK" ]; then
  fail "UVC 已回退物理镜头: $FALLBACK"
fi

section "3. 内核 UVC / V4L2"
UVC_NODES=""
for n in /sys/class/video4linux/video*/name; do
  [ -f "$n" ] || continue
  line="$(cat "$n" 2>/dev/null)"
  echo "$line" | grep -qi uvc && {
    dev="$(dirname "$n")"
    dev="${dev##*/}"
    log "$dev name=$line"
    UVC_NODES="$UVC_NODES $dev"
  }
done
[ -z "$UVC_NODES" ] && fail "未找到 UVC video 节点（未插采集卡或驱动未加载）"

section "4. vendor 配置"
if [ -f /vendor/etc/external_camera_config.xml ]; then
  log "--- /vendor/etc/external_camera_config.xml (head) ---"
  head -35 /vendor/etc/external_camera_config.xml 2>/dev/null | tee -a "$OUT"
else
  fail "缺少 /vendor/etc/external_camera_config.xml"
fi

section "5. dumpsys media.camera 摘要"
DUMP="$(dumpsys media.camera 2>/dev/null)"
if [ -z "$DUMP" ]; then
  fail "dumpsys media.camera 无输出"
else
  echo "$DUMP" | grep -E 'Number of camera|Camera [0-9]+|Device [0-9]+|LENS_FACING|ANDROID_LENS_FACING|external/' | head -80 | tee -a "$OUT"
  log "--- stream / orientation (camera 0 1 102) ---"
  for cid in 0 1 2 3 102; do
    echo "$DUMP" | grep -A3 "Camera $cid " | head -5 | while read -r line; do
      log "  id$cid: $line"
    done
  done
  log "--- active clients ---"
  echo "$DUMP" | grep -E 'Client PID|Camera ID|Package|In use|API level' | head -40 | tee -a "$OUT"
  log "--- UVC / external HAL ---"
  echo "$DUMP" | grep -E 'external|EXTERNAL|Provider.*external|HAL external' | head -30 | tee -a "$OUT"
fi

section "6. 逻辑推断（Open Camera API2 ID:1）"
log "当前 replace_role=$ROLE enabled=$ENABLED"
if [ "$ENABLED" = "0" ] || [ "$ROLE" = "off" ]; then
  log "ID:1 = 机身前摄（未走 UVC）。API2 失败请查前摄 HAL / 占用。"
elif [ "$ROLE" = "front" ]; then
  log "ID:1 应重定向到 external/102（UVC）。API2 失败重点查 UVC patch / configureStreams / initialize。"
elif [ "$ROLE" = "back" ]; then
  log "ID:1 = 真前摄；UVC 在 ID:0。若你在 Open Camera 选「前置」测 UVC，应改为后摄或设置里「替代前摄」。"
fi
echo "$DUMP" | grep -q 'external/102\|Camera 102\|external/10' && ok "dumpsys 可见 external 相机" || fail "dumpsys 未见 external 相机 → HAL/采集卡枚举失败"

section "7. 占用 / 冲突"
for pkg in com.android.camera2 org.lineageos.aperture com.ss.android.ugc.aweme; do
  if pm list packages 2>/dev/null | grep -q "$pkg"; then
    log "pkg_installed $pkg"
  fi
done
log "tip: force-stop 相机与抖音后再测 Open Camera API2"
log "  am force-stop com.android.camera2; am force-stop com.ss.android.ugc.aweme"

section "8. 镜像 / 旋转 HAL 侧"
log "mirror persist=$MIRROR_P vendor=$MIRROR_V rotation persist=$(prop persist.vendor.camera.uvc.rotation)"
if [ "$MIRROR_P" != "1" ]; then
  warn "左右镜像 persist 未开 → 设置 → 直播选项 → 左右镜像 → 应用（会重启 cameraserver）"
fi
log "match=$(prop vendor.camera.uvc.match) (native_portrait|landscape_rotated|landscape_no_rotation)"

section "9. 抖音扫脸 / 横屏拉伸"
log "常见原因: (1) 竖屏校正 90/270 未应用 (2) App 横屏 Surface 与 stream 宽高不一致"
log "       (3) rotate-and-crop 代理 (c2fix 应对 UVC 重定向关闭) (4) 镜像与 App 自拍镜像叠加"
log "vendor.rotation=$(prop vendor.camera.uvc.rotation) → External HAL I420Rotate + metadata"

section "10. 建议 logcat（PC 执行）"
log "adb logcat -c"
log "复现 Open Camera API2 前置 或 抖音扫脸 15 秒"
log "adb logcat -d -s UvcReplacePolicy:* CameraService:* Camera2ClientBase:* CameraDeviceClient:* ExtCamDevSsn@3.4:* > uvc-camera2.log"
log "或: adb shell uvc-troubleshoot log && ... && adb shell uvc-troubleshoot log pull"

section "11. 自动结论"
ISSUES=0
[ "$ENABLED" = "0" ] && { warn "无界总开关关"; ISSUES=$((ISSUES + 1)); }
[ -n "$FALLBACK" ] && ISSUES=$((ISSUES + 1))
echo "$DUMP" | grep -q external || ISSUES=$((ISSUES + 1))
if [ "$ROLE" = "back" ]; then
  warn "当前「替代后摄」：Open Camera 前置 ID:1 不是 UVC，若你要测 UVC+API2 请改「替代前摄」并应用"
fi
if [ "$ISSUES" -eq 0 ]; then
  ok "基础检查通过；若仍失败请上传本文件 + uvc-troubleshoot log pull 输出"
else
  fail "发现 $ISSUES 项基础问题，先按上文 [WARN]/[FAIL] 处理"
fi

log ""
log "报告已写入: $OUT"
log "拉取: adb pull $OUT"
echo "$OUT"
