#!/bin/bash

NUMMINOR=32	# maximum number of minor devices (must be <= CTLMINOR)
CTLMINOR=255	# control channel (do not change)
COWDIR=/dev/cow # base directory for all cow devices

#
# check if a major number has been specified as argument
#
if [ $# -ge 1 ]
then
	COWMAJOR=$1
else
	COWMAJOR=241
fi

#
# verify if the major number is numeric
#
if expr "$COWMAJOR" + 0 > /dev/null 2> /dev/null
then
	:
else
	echo $0: $1 is not numeric
	exit 1
fi

#
# create directory /dev/cow for all cow devices
#
if [ -d $COWDIR ]
then
	rm -rf $COWDIR
fi

if mkdir $COWDIR
then
	:
else
	echo $0: can not create directory $COWDIR
	exit 2
fi

#
# create device-special nodes below /dev/cow for cowloop driver
#
let COWMINOR=0

while [ $COWMINOR -lt $NUMMINOR ]
do
	if mknod $COWDIR/$COWMINOR b $COWMAJOR $COWMINOR
	then
		chmod o= $COWDIR/$COWMINOR
	else
		echo $0: can not make node $COWDIR/$COWMINOR
		exit 3
	fi

	let COWMINOR+=1
done

#
# create /dev/cowloop for compatibility (symlink to /dev/cow0)
#
if [ -e /dev/cowloop ]
then
	rm -f /dev/cowloop
fi

if ln -s $COWDIR/0 /dev/cowloop
then
	:
else
	echo $0: can not create symlink /dev/cowloop
	exit 4
fi

#
# create /dev/cow/ctl for control features
#
if mknod $COWDIR/ctl b $COWMAJOR $CTLMINOR 
then
	chmod o= $COWDIR/ctl
else
	echo $0: can not make node $COWDIR/ctl
	exit 3
fi

exit 0
