#!/bin/bash

# 退出码说明
# 0 - 成功
# 1 - 错误：等待TTY设备就绪超时
# 2 - 错误：未找到CH343驱动
# 3 - 错误：未找到含Qingheng的USB设备
# 4 - 错误：未找到对应USB地址
# 5 - 错误：未找到cdc_acm绑定的对应USB设备
# 6 - 错误：解绑cdc_acm驱动失败
# 7 - 错误：绑定usb_ch343驱动失败

# 变量设置
TTY_DEVICE="/dev/ttyACM*" # 替换为你要等待的tty设备路径
CDC_ACM_PATH="/sys/bus/usb/drivers/cdc_acm"
USB_CH343_PATH="/sys/bus/usb/drivers/usb_ch343"
CHECK_INTERVAL=1 # 检查设备就绪的时间间隔（秒）
MAX_WAIT_SECONDS=30 # 最大等待时间（秒），0表示无限等待

# 初始化变量
start_time=$(cut -d. -f1 /proc/uptime)
current_time=0
qinheng_id=""
usb_address=""
vendor_id=""
product_id=""
cdc_acm_sub_addr=""


# ----------------- 1. 等待TTY设备就绪 -----------------
# 循环等待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 ls /sys/bus/usb/drivers/usb_ch343 > /dev/null 2>&1; then
    echo "[雷达驱动自动切换程序] 检测到CH343驱动存在，继续执行..." > /dev/kmsg
else
    echo "[雷达驱动自动切换程序] 错误：未找到CH343驱动！" > /dev/kmsg
    exit 2
fi


# ------------- 3. 查找Qingheng对应的usb接口 -------------
echo "[雷达驱动自动切换程序] 开始提取QinHeng设备ID..." > /dev/kmsg

# 执行lsusb并过滤含QinHeng的行，提取ID（核心逻辑）
qinheng_id=$(lsusb | grep "QinHeng" | awk '{print $6}' | head -n 1)

# 检查是否提取到ID
if [ -z "${qinheng_id}" ]; then
    echo "[雷达驱动自动切换程序] 错误：未找到含QinHeng的USB设备！" > /dev/kmsg
    exit 3 
else
    echo "[雷达驱动自动切换程序] 成功提取QinHeng设备ID：${qinheng_id}" > /dev/kmsg
    # 将ID拆分为vendor_id和product_id
    vendor_id=$(echo "${qinheng_id}" | cut -d ':' -f 1)
    product_id=$(echo "${qinheng_id}" | cut -d ':' -f 2)
fi

# -------------------- 4. 提取USB地址 --------------------
echo "[雷达驱动自动切换程序] 开始查找idVendor=${vendor_id},idProduct=${product_id}的USB地址..." > /dev/kmsg
# 核心命令：过滤dmesg日志，提取USB地址
usb_address=$(dmesg | grep -E "idVendor=${vendor_id}, idProduct=${product_id}" | grep -oE "usb [0-9]+-[0-9.]+:" | awk '{print $2}' | sed 's/://' | tail -n 1)

# 检查是否提取到USB地址
if [ -z "${usb_address}" ]; then
    echo "[雷达驱动自动切换程序] 错误：未找到对应USB地址" > /dev/kmsg
    exit 4
else
    echo "[雷达驱动自动切换程序] 成功找到USB地址：${usb_address}" > /dev/kmsg
fi

# ---- 5. 找到cdc_acm驱动对应的usb设备 ----
echo "[雷达驱动自动切换程序] 开始从${CDC_ACM_PATH}提取${usb_address}对应的子地址..." > /dev/kmsg

cdc_acm_sub_addr=$(ls "${CDC_ACM_PATH}" 2>/dev/null | grep "^${usb_address}:" | head -n 1)
    
if [ -z "${cdc_acm_sub_addr}" ]; then
    echo "[雷达驱动自动切换程序] 错误：${CDC_ACM_PATH}中未找到${usb_address}绑定的对应USB设备" > /dev/kmsg
    exit 5
else
    echo "[雷达驱动自动切换程序] 成功提取cdc_acm子地址：${cdc_acm_sub_addr}" > /dev/kmsg
fi

# 6. 切换驱动
echo "[雷达驱动自动切换程序] 开始切换cdc_acm驱动到USB地址${usb_address}..." > /dev/kmsg

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

echo "${cdc_acm_sub_addr}" | sudo tee "${USB_CH343_PATH}/bind" 2>/dev/null
if [ $? -eq 0 ]; then
    echo "[雷达驱动自动切换程序] 成功绑定usb_ch343驱动：${cdc_acm_sub_addr}" > /dev/kmsg
else
    echo "[雷达驱动自动切换程序] 错误：绑定usb_ch343驱动失败（检查驱动是否加载）" > /dev/kmsg
    exit 7
fi


# 执行完成
echo "[雷达驱动自动切换程序] 雷达驱动自动切换完毕！" > /dev/kmsg

exit 0