#!/bin/bash

function die()
{
	echo $@ >&2
	exit -1
}

module="dvbstub1"
device="dvbstubi"
device_count=10
mode="664"

LOAD=y
UNLOAD=

while [ "$1" != "" ] ; do

	case "$1" in
		"-c") # Check - unload
		CHECK=y
		;;
		"-u") # Unload
		UNLOAD=y
		LOAD=
		;;
		*)
		UNLOAD_OPTS="$UNLOAD_OPTS $1"
		;;
	esac
	shift
done


LOAD_OPTS=$UNLOAD_OPTS

if [ -n "$LOAD" ] ; then

	if [ -n "$CHECK" ] ; then
		lsmod | grep $module >/dev/null
		test "$?" = "0" && skip_load=y
	fi

	if [ -z "$skip_load" ] ; then

		# Group: since distributions do it differently, look for wheel or use staff
		if grep -q '^users:' /etc/group; then
			group="users"
		else
			group="wheel"
		fi

		# invoke insmod with all arguments we got
		# and use a pathname, as insmod doesn't look in . by default
		/sbin/insmod ./$module.ko $LOAD_OPTS || die "insmod failed"

		# retrieve major number
		major=$(awk "\$2==\"$device\" {print \$1}" /proc/devices)
		test -z "$major" && die "Can't find major number of $module. Check /proc/devices"

		for ((i=0; i<$device_count; i=i+1)) ; do
			echo "Creating node for /dev/${device}$i"
			rm -f /dev/${device}$i
			mknod /dev/${device}$i c $major $i
			chgrp $group /dev/${device}$i
			chmod $mode  /dev/${device}$i
		done

		ln -sf ${device}0 /dev/${device}
	fi
fi

if [ -n "$UNLOAD" ] ; then

	if [ -n "$CHECK" ] ; then
		lsmod | grep $module >/dev/null
		test "$?" != "0" && skip_unload=y
	fi

	if [ -z "$skip_unload" ] ; then
		# invoke rmmod with all arguments we got
		/sbin/rmmod $UNLOAD_OPTS $module || exit 1

		# Remove stale nodes
		rm -f /dev/${device}
		for ((i=0; i<$device_count; i=i+1)) ; do
			rm -f /dev/${device}$i
		done
	fi
fi


