#/bin/sh
#This script is used to systemd environment

VID=1415:c20d
VEX112=1441:0080
VEX142=1440:0080
VEX114=1441:0091
VEX144=1440:0091


#unbind device
VEX112_a=(`lspci -Dkn | grep -B 1 $VEX112 | grep $VID | awk '{print $1}'`)

for ((index=0; index<${#VEX112_a[@]}; index++)); do
	BUS=`echo ${VEX112_a[$index]} | awk -F: '{printf $2}'`
	if [ -e /sys/class/pci_bus/0000\:$BUS/device/0000\:$BUS\:00.1/driver/ ]; then
		grep serial8250_icpdas /sys/class/pci_bus/0000\:$BUS/device/0000\:$BUS\:00.1/uevent > /dev/null
		if [ $? == 1 ]; then
		echo ${VEX112_a[$index]} is VEX112 unbind VEX112
		echo "${VEX112_a[$index]}" > /sys/class/pci_bus/0000\:$BUS/device/0000\:$BUS\:00.1/driver/unbind
		fi
	fi
done

VEX142_a=(`lspci -Dkn | grep -B 1 $VEX142 | grep $VID | awk '{print $1}'`)

for ((index=0; index<${#VEX142_a[@]}; index++)); do
        BUS=`echo ${VEX142_a[$index]} | awk -F: '{printf $2}'`
        if [ -e /sys/class/pci_bus/0000\:$BUS/device/0000\:$BUS\:00.1/driver/ ]; then
		grep serial8250_icpdas /sys/class/pci_bus/0000\:$BUS/device/0000\:$BUS\:00.1/uevent > /dev/null
		if [ $? == 1 ]; then
		echo ${VEX142_a[$index]} is VEX142 unbind VEX142
        	echo "${VEX142_a[$index]}" > /sys/class/pci_bus/0000\:$BUS/device/0000\:$BUS\:00.1/driver/unbind
		fi
        fi
done

VEX114_a=(`lspci -Dkn | grep -B 1 $VEX114 | grep $VID | awk '{print $1}'`)

for ((index=0; index<${#VEX114_a[@]}; index++)); do
        BUS=`echo ${VEX114_a[$index]} | awk -F: '{printf $2}'`
        if [ -e /sys/class/pci_bus/0000\:$BUS/device/0000\:$BUS\:00.1/driver/ ]; then
		grep serial8250_icpdas /sys/class/pci_bus/0000\:$BUS/device/0000\:$BUS\:00.1/uevent > /dev/null
		if [ $? == 1 ]; then
		echo ${VEX114_a[$index]} is VEX114 unbind VEX114
        	echo "${VEX114_a[$index]}" > /sys/class/pci_bus/0000\:$BUS/device/0000\:$BUS\:00.1/driver/unbind
		fi
        fi
done

VEX144_a=(`lspci -Dkn | grep -B 1 $VEX144 | grep $VID | awk '{print $1}'`)

for ((index=0; index<${#VEX144_a[@]}; index++)); do
        BUS=`echo ${VEX144_a[$index]} | awk -F: '{printf $2}'`
        if [ -e /sys/class/pci_bus/0000\:$BUS/device/0000\:$BUS\:00.1/driver/ ]; then
		grep serial8250_icpdas /sys/class/pci_bus/0000\:$BUS/device/0000\:$BUS\:00.1/uevent > /dev/null
		if [ $? == 1 ]; then
		echo ${VEX144_a[$index]} is VEX144 unbind VEX144
        	echo "${VEX144_a[$index]}" > /sys/class/pci_bus/0000\:$BUS/device/0000\:$BUS\:00.1/driver/unbind
		fi
        fi
done

#kill Modem
grep Fedora /etc/issue > /dev/nulll
if [ $? == 0 ]; then
	systemctl list-units | grep ModemManager > /dev/null
	if [ $? == 0 ]; then
		Modem=`ps aux | grep /usr/sbin/ModemManager | head -1 | awk '{print $2}'`
		kill $Modem
	fi
else
	echo 
fi

#insmod driver
lsmod | grep icpdas_8250 > /dev/null
if [ $? == 1 ]; then
	insmod ./icpdas_8250_dma.ko
	insmod ./icpdas_8250_port.ko
	insmod ./icpdas_8250.ko
fi

lsmod | grep icpdas_8250_pci > /dev/null
if [ $? == 1 ]; then
	insmod ./icpdas_8250_pci.ko
fi

echo "Install OK!"
