#!/bin/sh
#$Id: mconf,v 1.1 2002/09/11 14:25:17 chris Exp $
#
# configure device major number to use for aksparlnx
# creates /opt/aksparlnx/etc/major
# must be run as root

usage() {
    echo "usage: $0 -force | -update"
    exit 1
}

# make /dev/Hardlock special file using NEWMAJOR
mkhldev() {
    rm -f /dev/Hardlock
    mknod /dev/Hardlock c $NEWMAJOR 0
    chmod 666 /dev/Hardlock
    exit 0
}

# checks whether /opt/aksparlnx/etc/major and /dev/Hardlock have the
# correct major number and update them if not (using NEWMAJOR)
checkmajor() {
    if [ $NEWMAJOR -eq 0 ]; then    # sanity check
	echo "internal error. aborted!"
	exit 1
    fi
    if [ -f $outfile ]; then
	. $outfile
    else
	MAJOR=0
    fi
    if [ $MAJOR -ne $NEWMAJOR ]; then
	#echo "updating $outfile"
	echo "MAJOR=$NEWMAJOR" > $outfile
    fi
    if [ -c /dev/Hardlock ]; then    # /dev/Hardlock already exists
	hlls=$(ls -l /dev/Hardlock | sed 's/\ \+/ /g')
	HLMAJ=$(echo $hlls | cut -d\  -f5 | sed s/,//)
	HLMIN=$(echo $hlls | cut -d\  -f6)
	if [ $HLMIN -ne 0 -o $HLMAJ -ne $NEWMAJOR ]; then
	    mkhldev
	    exit 0
	fi
	chmod 666 /dev/Hardlock
    fi
    mkhldev
}

outfile=/opt/aksparlnx/etc/major
FORCE=no
NEWMAJOR=0

if [ $# -ne 1 ]; then usage; fi
if [ "$1" != "-force" -a "$1" != "-update" ]; then usage; fi
if [ "$1" = "-force" ]; then FORCE=yes; fi

# if not force, check whether aksparlnx already exists
if [ $FORCE = "no" ]; then
    if grep aksparlnx /proc/devices > /dev/null 2>&1; then
	# aksparlnx present
	NEWMAJOR=$(grep aksparlnx /proc/devices | sed 's/^ *\(.*\)/\1/' | cut -f1 -d\  )
	#echo "major = $NEWMAJOR"
	checkmajor;
	exit 0;
    fi
fi

# find a free major device number in the range 42,60-63,240-254

devices_in_use="$(cat /proc/devices | sed -e '/^$/,//d' -e '/Character devices:/d' -e 's/^ *\(.*\)/\1/' | cut -d\  -f1)"

for NEWMAJOR in 60 61 62 63 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 42; do
    #echo "checking $NEWMAJOR:"
    if ! echo $devices_in_use | tr \  \\n | grep ^$NEWMAJOR\$ > /dev/null 2>&1; then
	#echo "found free: $NEWMAJOR"
	checkmajor
	exit 0
    fi
done
