#!/usr/bin/env bash
set -euo pipefail

echo "=== USB devices (candidate CAN adapters) ==="
# 先列出所有USB设备，方便你看到Vendor/Product
lsusb

echo
echo "=== Finding candidate USB devices by vendor/product (you may need to adjust filters) ==="
echo "Tip: if you know VID:PID, set VIDPID like: VIDPID=1d50:606f ./probe_canalystii_ports.sh"
VIDPID="${VIDPID:-}"
if [[ -n "${VIDPID}" ]]; then
  lsusb | grep -i "${VIDPID}" || true
else
  echo "(No VIDPID specified. We'll show details for all USB devices; you can narrow it later.)"
fi

echo
echo "=== Enumerate /dev/bus/usb/*/* and print stable attributes ==="

# 遍历所有 USB device node，提取关键属性：idVendor/idProduct + DEVPATH + KERNELS(物理端口链)
for devnode in /dev/bus/usb/*/*; do
  # 过滤：如果设置了VIDPID，则只看匹配的
  if [[ -n "${VIDPID}" ]]; then
    info=$(udevadm info -a -n "$devnode" 2>/dev/null | head -n 80 || true)
    echo "$info" | grep -qi "ATTR{idVendor}==\"${VIDPID%%:*}\"" || continue
    echo "$info" | grep -qi "ATTR{idProduct}==\"${VIDPID##*:}\"" || continue
  fi

  # udev属性输出
  path=$(udevadm info -q path -n "$devnode" 2>/dev/null || true)
  [[ -z "$path" ]] && continue

  props=$(udevadm info -q property -n "$devnode" 2>/dev/null || true)
  vid=$(echo "$props" | awk -F= '/^ID_VENDOR_ID=/{print $2}')
  pid=$(echo "$props" | awk -F= '/^ID_MODEL_ID=/{print $2}')
  busnum=$(echo "$props" | awk -F= '/^BUSNUM=/{print $2}')
  devnum=$(echo "$props" | awk -F= '/^DEVNUM=/{print $2}')

  [[ -z "$vid" || -z "$pid" ]] && continue

  # 取 KERNELS 链：包含类似 2-3 / 1-1.2 这种物理端口信息
  kernels=$(udevadm info -a -n "$devnode" 2>/dev/null | awk -F'==' '/KERNELS==/{print $2}' | head -n 8 | tr -d '"' | tr '\n' ' ')

  echo "----"
  echo "DEVNODE : $devnode"
  echo "VID:PID : ${vid}:${pid}"
  echo "BUS/DEV : ${busnum:-?}/${devnum:-?}"
  echo "DEVPATH : $path"
  echo "KERNELS : $kernels"
done

echo
echo "=== Next steps ==="
echo "1) Identify the two CANalyst-II devices (same VID:PID) but different KERNELS like 2-3 and 2-4"
echo "2) Use those KERNELS values to write udev rules mapping them to /dev/canalyst_left and /dev/canalyst_right"
