#!/bin/bash

# 退出码说明
# 0 - 成功
# 1 - 错误：等待TTY设备就绪超时
# 2 - 错误：未找到CH343驱动
# 3 - 错误：雷达端口上未找到CH34x设备
# 4 - 错误：未从cdc_acm找到雷达接口
# 5 - 错误：解绑cdc_acm驱动失败
# 6 - 错误：绑定usb_ch343驱动失败

# ── 配置 ────────────────────────────────────────────
TTY_DEVICE="/dev/ttyACM*"
CDC_ACM_PATH="/sys/bus/usb/drivers/cdc_acm"
USB_CH343_PATH="/sys/bus/usb/drivers/usb_ch343"
RADAR_USB_PORT="1-1.4"          # 雷达 CH34x 的 USB 物理端口（固定不变）
CHECK_INTERVAL=1
MAX_WAIT_SECONDS=30

# ── 初始化 ──────────────────────────────────────────
start_time=$(cut -d. -f1 /proc/uptime)

# ── 1. 等待 TTY 设备就绪 ────────────────────────────
while true; do
    for dev in /dev/ttyACM*; do
        [ -e "$dev" ] || continue
        if [ -c "$dev" ] && [ -r "$dev" ] && [ -w "$dev" ]; then
            echo "[雷达驱动自动切换程序] 设备 $dev 已就绪！" > /dev/kmsg
            TTY_DEVICE="$dev"
            break 2
        fi
    done

    if [ ${MAX_WAIT_SECONDS} -gt 0 ]; then
        current_time=$(cut -d. -f1 /proc/uptime)
        elapsed_seconds=$((current_time - start_time))
        if [ ${elapsed_seconds} -ge ${MAX_WAIT_SECONDS} ]; then
            echo "[雷达驱动自动切换程序] 错误：等待 ${TTY_DEVICE} 超时（${MAX_WAIT_SECONDS}秒）！" > /dev/kmsg
            exit 1
        fi
        echo "[雷达驱动自动切换程序] 仍在等待${TTY_DEVICE}（已等待${elapsed_seconds}秒）..." > /dev/kmsg
    fi
    sleep ${CHECK_INTERVAL}
done

# ── 2. 确认 CH343 驱动已加载 ────────────────────────
if [ -d "${USB_CH343_PATH}" ]; then
    echo "[雷达驱动自动切换程序] CH343驱动已加载，继续..." > /dev/kmsg
else
    echo "[雷达驱动自动切换程序] 错误：未找到CH343驱动！" > /dev/kmsg
    exit 2
fi

# ── 3. 通过物理端口定位雷达 CH34x ───────────────────
radar_sysfs="/sys/bus/usb/devices/${RADAR_USB_PORT}"

if [ ! -d "${radar_sysfs}" ]; then
    echo "[雷达驱动自动切换程序] 错误：端口 ${RADAR_USB_PORT} 上无设备！" > /dev/kmsg
    exit 3
fi

vendor_id=$(cat "${radar_sysfs}/idVendor" 2>/dev/null)
product_id=$(cat "${radar_sysfs}/idProduct" 2>/dev/null)

if [ "${vendor_id}" != "1a86" ] || [ "${product_id}" != "55d4" ]; then
    echo "[雷达驱动自动切换程序] 错误：端口 ${RADAR_USB_PORT} 上 VID:PID=${vendor_id}:${product_id}，非雷达CH34x！" > /dev/kmsg
    exit 3
fi

echo "[雷达驱动自动切换程序] 雷达确认位于端口 ${RADAR_USB_PORT}，VID:PID=${vendor_id}:${product_id}" > /dev/kmsg

# ── 4. 查找 cdc_acm 下雷达的接口 ────────────────────
cdc_acm_sub_addr=$(ls "${CDC_ACM_PATH}" 2>/dev/null | grep "^${RADAR_USB_PORT}:" | head -n 1)

if [ -z "${cdc_acm_sub_addr}" ]; then
    echo "[雷达驱动自动切换程序] 错误：cdc_acm驱动中未找到端口 ${RADAR_USB_PORT} 的接口" > /dev/kmsg
    exit 4
fi

echo "[雷达驱动自动切换程序] 雷达 cdc_acm 接口：${cdc_acm_sub_addr}" > /dev/kmsg

# ── 5. 解绑 cdc_acm ─────────────────────────────────
echo "${cdc_acm_sub_addr}" | sudo tee "${CDC_ACM_PATH}/unbind" > /dev/null 2>&1
if [ $? -eq 0 ]; then
    echo "[雷达驱动自动切换程序] 已解绑 cdc_acm：${cdc_acm_sub_addr}" > /dev/kmsg
else
    echo "[雷达驱动自动切换程序] 错误：解绑 cdc_acm 失败" > /dev/kmsg
    exit 5
fi

# ── 6. 绑定 ch343 ───────────────────────────────────
echo "${cdc_acm_sub_addr}" | sudo tee "${USB_CH343_PATH}/bind" > /dev/null 2>&1
if [ $? -eq 0 ]; then
    echo "[雷达驱动自动切换程序] 已绑定 usb_ch343：${cdc_acm_sub_addr}" > /dev/kmsg
else
    echo "[雷达驱动自动切换程序] 错误：绑定 usb_ch343 失败" > /dev/kmsg
    exit 6
fi

echo "[雷达驱动自动切换程序] 雷达驱动切换完毕！" > /dev/kmsg
exit 0
