#!/bin/bash

here=`dirname $0`
me=`basename $0`
module="vdag"
device="dag"
group="root"
mode="664"
maxnum=31

do_help () {
cat <<EOF

This helper script loads the $module driver and creates /dev device nodes.

Usage: $me [options] [driveropts]

Options:
	-h	Help
	-n <X>	Number of $module device nodes to create

Any remaining [driveropts] options are passed to the $module driver.

EOF
}

do_load () {
    ( /sbin/modprobe $module $DRIVEROPTS 2>&1 || exit 1 ) | grep -v taint
    
    if [ "`lsmod | grep $module`" ] ; then
        echo $me: $module driver loaded
    else
        echo "$me: Error, 'modprobe $module$DRIVEROPTS' failed!"
	do_help;
	exit 1
    fi
}

TEMP=`getopt -n $me -o hn: -- "$@"`
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

eval set -- "$TEMP"

while true ; do
    case "$1" in
	-h) do_help; exit 0 ;;
	-n) numnode=$2 ; shift 2 ;;
	--) shift ; break ;;
	*) echo "Internal error!" ; exit 1 ;;
    esac
done

for arg do DRIVEROPTS="$DRIVEROPTS $arg"; done
#echo "$me: driver options:$DRIVEROPTS"

if [ -z "$numnode" ];
then
    numnode=15
else
    let "numnode=$numnode-1"
fi;

if [ "`lsmod | grep $module`" ] ; then
    if [ -z "$DRIVEROPTS" ] ; then
	echo $me: $module driver previously loaded, skipping
    else
	echo $me: $module driver previously loaded, unloading
	/sbin/rmmod $module 2>&1
	echo $me: loading $module driver with new options
	do_load;
    fi
else
    echo $me: $module driver is not loaded, loading now
    do_load;
fi

cd $here

major=`cat /proc/devices | awk "\\$2==\"$module\" {print \\$1}" | head -n 1`
# Remove all stale nodes and replace them, then give gid and perms

for i in `seq 16 $maxnum` ; do

    rm -f /dev/${device}${i}
    rm -f /dev/${device}iom${i}

done

let "numnode=$numnode+16"

for i in `seq 16 $numnode` ; do

    mknod /dev/${device}$i  c  $(($major))  $i
    mknod /dev/${device}iom$i c $(($major+1)) $i 

    chgrp $group /dev/${device}$i
    chgrp $group /dev/${device}iom$i

    chmod $mode  /dev/${device}$i
    chmod $mode  /dev/${device}iom$i

done
