#/bin/bash
#20220718
#List card's information

EXAR_VID=13a8

#unbind PCIe-series device
PCIe_unbind=(`lspci -Dkn | grep $EXAR_VID | awk '{print $1}'`)				#PCIe domain numbers

lsmod | grep xr17v35x > /dev/null
if [ $? != 0 ]; then
        echo "Driver not install."
        exit
fi

# 5. Scan and list mapping from PCI hardware to TTY device nodes
echo "---------------------------------------"
for ((index=0; index<${#PCIe_unbind[@]}; index++)); do
    ADDR=${PCIe_unbind[$index]}

    # Retrieve Subsystem IDs via lspci
    SVID_SDID=$(lspci -Dkn -s "$ADDR" | grep -A 1 "$ADDR" | grep Subsystem | awk '{print $2}')

    # Identify board model and port count based on Subsystem IDs
    PORT=0
    case "$SVID_SDID" in
        1441:0080 ) echo -n "PCIe-S112 mode 232, "; PORT=1;;
        1440:0080 ) echo -n "PCIe-S142 mode 485, "; PORT=1;;
        1441:0091 ) echo -n "PCIe-S114 mode 232, "; PORT=3;;
        1440:0091 ) echo -n "PCIe-S144 mode 485, "; PORT=3;;
        1441:00a0 ) echo -n "PCIe-S118 mode 232, "; PORT=7;;
        1440:00a0 ) echo -n "PCIe-S148 mode 485, "; PORT=7;;
        * ) echo -n "Unknown Device ($SVID_SDID), "; PORT=0;;
    esac

    # Robust detection: Search /sys/class/tty for nodes linked to this PCI address.
    # This works even with nested sysfs structures in newer kernels (6.x+).
    TTY_NODE=$(ls -l /sys/class/tty/ttyXR* 2>/dev/null | grep "$ADDR" | awk -F'/' '{print $NF}' | head -n 1)

    if [ -n "$TTY_NODE" ]; then
        # Extract the base number from the node name (e.g., "ttyXR12" -> "12")
        BASE_NUM=$(echo "$TTY_NODE" | sed 's/[^0-9]*//g')
        END_NUM=$((BASE_NUM + PORT))
        echo "tty$TTY_NODE to ttyXR$END_NUM"
    else
        echo "Error: Could not find ttyXR nodes for hardware at $ADDR"
    fi
done
echo "---------------------------------------"

