#!/bin/sh

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

# Stop mxupcie before resetting any hardware
if grep -q "^${MOXA_DRIVER} " /proc/modules; then
	modprobe -r "$MOXA_DRIVER" || exit $?
fi

# Get Moxa devices' bus information
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
		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
			fi
		done
	fi
done

# Reprobe the mxupcie driver if it is installed for the running kernel
if modinfo "$MOXA_DRIVER" >/dev/null 2>&1; then
	modprobe "$MOXA_DRIVER"
fi