#!/bin/sh
#

MOXA_DRIVER=mxupcie
MOXA_VENDOR=1393
MOXA_DEVICE="1024 1025 1322 1144 1045 1683 1182 1183 1381 1342 1160 1161"
REPROBE_MOXA_DRIVER=0

# Get moxa devices' bus info
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
		# BUS_INFO is not empty
		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 pcie device driver
				echo $j > /sys/bus/pci/devices/$j/driver/unbind
				# reset pci device
				echo 1 > /sys/bus/pci/devices/$j/reset
				# reprobe mxupcie
				if lsmod | grep -q $MOXA_DRIVER ; then
					rmmod $MOXA_DRIVER
				fi
				modprobe $MOXA_DRIVER
			fi
		done
	fi
done
