#!/bin/sh
#

MOXA_DRIVER=mxupcie
MOXA_VENDOR=1393
MOXA_DEVICE="1024 1025 1027 1045 1046 1121 1144 1145 1160 1161 1182 1183 1322 1323 1342 1343 1381 1683"
REPROBE_MOXA_DRIVER=0

# Get the bus information of each Moxa device ID
echo "$MOXA_DEVICE" | tr ' ' '\n' | while read i; do
	VEN_DEV="${MOXA_VENDOR}:${i}"
	BUS_INFO=`lspci -D -n | grep $VEN_DEV | cut -c 1-12`

	if [ -n "$BUS_INFO" ]; then
		# Use a while loop to read BUS_INFO and handle identical devices
		echo "$BUS_INFO" | while read j; do
			REPROBE_MOXA_DRIVER=0

			if [ -d "/sys/bus/pci/drivers/8250_moxa/${j}" ]; then
				REPROBE_MOXA_DRIVER=1
			elif  [ -d "/sys/bus/pci/drivers/serial/${j}" ]; then
				REPROBE_MOXA_DRIVER=1
			fi

			if [ "$REPROBE_MOXA_DRIVER" -eq "1" ]; then
				# Unbind the built-in driver from the device
				echo $j > /sys/bus/pci/devices/$j/driver/unbind
				# Reset the device
				echo 1 > /sys/bus/pci/devices/$j/reset
			fi
		done
	fi
done
# Reprobe the mxupcie driver
if lsmod | grep -q $MOXA_DRIVER; then
	rmmod $MOXA_DRIVER
	modprobe $MOXA_DRIVER
fi
