#!/bin/bash

# Use only with kernel 2.6
# Load the APCI-1696 and create the device node
# under /dev/apci1696 and the minor number of the board.

DRIVER_NAME="apci1696"
BOARD_NAME="apci1696"
MODULE_NAME="$BOARD_NAME.ko"
VENDOR_DEVICE_ID="15b8100a"

# checking privileges
if [ `id -u` -ne 0 ];
then
        echo "$0: You must have root privileges to run this script shell"
        exit 1
fi

# Test the kernel version
if [ `uname -r | cut -d'.' -f 2` -ne 6 ];
then
        echo "$0: This script is only for kernel 2.6.X"
        exit 1
fi

# Search the number of apci-1696 in the computer
NBOARDS=$(grep -cR $VENDOR_DEVICE_ID /proc/bus/pci/devices)

# Board found?
if [ $? -eq 1 ]; then
        echo "Fail to detectd $BOARD_NAME"
        exit 1
fi

if [ $NBOARDS -eq 0 ]; then
        echo "No $BOARD_NAME detected"
        exit 1
fi

echo "$NBOARDS $BOARD_NAME detected"

cat /proc/modules | grep $BOARD_NAME > /dev/null

if [ $? -eq 0 ]; then
    echo "driver for $MODULE_NAME already loaded"
else
	echo "loading driver $MODULE_NAME"
	insmod $MODULE_NAME || exit 1
fi

# Search the major number
MAJOR=`grep $DRIVER_NAME /proc/devices | cut -f 1 -d ' '`

if [ "$MAJOR" == "" ]
then
	echo "No module with name $DRIVER_NAME found"
    exit 1
fi

mkdir -p "/dev/$BOARD_NAME" || exit 1

# Create nodes
i=0
while [ $i -lt $NBOARDS ]; do

    if [ -a "/dev/$BOARD_NAME/$i" ]; then
    	rm "/dev/$BOARD_NAME/$i"
    fi

	mknod /dev/$BOARD_NAME/$i c $MAJOR $i || exit 1
    chmod 666 /dev/$BOARD_NAME/$i || exit 1
    echo "Created node /dev/$BOARD_NAME/$i"

    i=$((i+1))
done

exit 0


