#!/bin/bash

DSP_INTERFACE_CFG=/etc/fiad-conf/sysconfig/network-scripts/ifcfg-lan0_0
DSP_MAC_ADDRESS_CFG=/proc/dspmac
DSPCARD_DRIVER_PATH=/lib/modules/epygi

# determine the version of kernel
K_VER_EXP=3.10.0-514.26.2.el7.centos.plus.i686
K_VER_CURRENT=$(uname -r)
min=$(echo -e $K_VER_EXP"\n"$K_VER_CURRENT|sort -V|head -n 1)
HIGHER_KERNEL=0
if [ "$min" = "$K_VER_EXP" ];then HIGHER_KERNEL=1;fi
##################################

do_start ()
{
	echo "Detecting and configuring DSP card"
	
	echo -n "   detecting card: "
	# Create the 8139 PCI devices I/O port list
	ports=$(lspci -vn | grep -A 4 '10ec:8168' | grep 'ports at' | awk '{print $4}')
	if [ -z "$ports" ]; then
		ports=$(lspci -vn | grep -A 4 '10ec:8139' | grep 'ports at' | awk '{print $4}')
	fi

	portsint=$(echo $ports |tr '[a-z]' '[A-z]' |sed 's/ / p /g' |sed 's/$/ p/'|awk '{print "16i "$0}'|dc |tr '\n' ',' | sed '$s/.$//')
    
	if [ -z "$portsint" ]; then
		echo " ERROR: there is no RealTek RTL-8139 compatible PCI ethernet cards detected"
		exit 1
	fi
	echo "  found"

	# Load dsp_card module
	echo -n "   loading pci_dsp_card kernel module: "
	insmod $DSPCARD_DRIVER_PATH/pci_dsp_card.ko portlist=$portsint> /dev/null 2>&1
	echo "  done"

	echo -n "   creating /dev/dspcard device: "
	# Find the dspcard device major number from the log
	
	#major=$(nbcat /var/log/messages | grep 'dspcard: Assigned major number' | awk '{print $10}' | tail -1)
	major=$(awk '$2=="dspcard" {print $1}' /proc/devices)
	if [ -z "$major" ] ; then
		major=$(dmesg | grep 'dspcard: Assigned major number' | awk '{print $5}' | tail -1)
	fi
	mknod "/dev/dspcard" c $major 0
	echo "  major number $major - done"

	echo "   configuring network interface using $DSP_INTERFACE_CFG values: "
	. $DSP_INTERFACE_CFG
	/bin/cat $DSP_MAC_ADDRESS_CFG > /tmp/tmp_dspmac; . /tmp/tmp_dspmac; rm -f /tmp/tmp_dspmac
	
	return
}

do_stop ()
{
	echo -n "Unloading the dspcard driver:"
	rmmod pci_dsp_card > /dev/null 2>&1
	rm /dev/dspcard
	echo "  done"
	
	echo -n "Shutting down DSP interface:"
	. $DSP_INTERFACE_CFG
	ifconfig $DEVICE down
	echo "  done"
	
	return
}

do_status ()
{
	echo "Sorry.. not yet implemented"
	exit 1
}

case "$1" in
	start)
		do_start
		;;
	stop)
		do_stop
		;;
	status)
		do_status
		;;
	restart)
		do_stop
		do_start
		;;
	*)
		echo "Usage: $0 {start|stop|restart|status}"
		exit 1
esac

exit $?
