#!/bin/bash
#
# This script is part of the cowloop-distribution.
# It is executed as a step in the 'make install' operation
# (in the sub-step "install-dev"). It creates the /dev files.
# /dev files must exist before you start using the cowloop-driver.
#
# This script may be run with two optional arguments but these are
# only needed under very special circumstances; please study the
# script if you want to know more.
#
# AT Consultancy, Nijmegen, The Netherlands

COWMAJOR=241    # major device number; overruled by $1
DFLCOWS=16	# default number of minor devices (must be <= CTLMINOR)
CTLMINOR=255	# control channel minor number (do not change)
COWDIR=/dev/cow # base directory for all cow devices; chrooted by $2

#
# Check if a major number has been specified as the
# first argument. It's optional; default is COWMAJOR
# The make-install step *does not* use the default, but
# explicity sends a $1 parameter (which holds the value
# of COWMAJOR as defined in the Makefile)
#
if [ $# -ge 1 ]
then
	COWMAJOR=$1
fi
#
# Optional second argument with the target rootdir.
# This name will be prepended before /dev/cow/....
# to provide a /dev-directory lower than usual.
# This facility is for very special circumstances only.
#
DESTDIR="$2"

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

#
# Create directory /dev/cow for all cow devices
#
if [ -d ${DESTDIR}$COWDIR ]
then
	rm -rf ${DESTDIR}$COWDIR
fi

if mkdir -p ${DESTDIR}$COWDIR
then
	:
else
	echo $0: can not create directory ${DESTDIR}$COWDIR >&2
	exit 2
fi

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

while [ $COWMINOR -lt $DFLCOWS ]
do
	if mknod ${DESTDIR}$COWDIR/$COWMINOR b $COWMAJOR $COWMINOR
 	then
		chmod o= ${DESTDIR}$COWDIR/$COWMINOR
 	else
		echo $0: can not make node ${DESTDIR}$COWDIR/$COWMINOR >&2
 		exit 3
 	fi

	let COWMINOR+=1
done

# Old device name /dev/cowloop (alternative to /dev/cow/0)
# supported for reasons of backward compatibility. Create it.
# See man-page cowdev(1) for more information.
if [ -e $DESTDIR/dev/cowloop ]
then
	rm -f $DESTDIR/dev/cowloop
fi
 
if ln -s $COWDIR/0 $DESTDIR/dev/cowloop
then
	:
else
	echo $0: can not create symlink $DESTDIR/dev/cowloop >&2
	exit 4
fi
 
#
# Create /dev/cow/ctl for the control channel mechanism
# See man-page cowdev(4) for more information.
#
if mknod ${DESTDIR}$COWDIR/ctl b $COWMAJOR $CTLMINOR 
then
	chmod o= ${DESTDIR}$COWDIR/ctl
else
	echo $0: can not make node ${DESTDIR}$COWDIR/ctl >&2
	exit 3
fi

exit 0
