#!/bin/sh
#
# $NetBSD: block-file-nbsd,v 1.3 2006/04/18 15:29:36 jlam Exp $
#
# Usage: block-file bind file [flags]
#
#    The file argument is the path to the file to which a vnd(4) device
#    will be bound.  The flags argument is an optional block of flags
#    to modify how the file is bound to the vnd(4) device.  The valid
#    flags are:
#
#	r	bind the file as read-only
#
# Usage: block-file unbind node
#
#    The node argument is the name of the device node to unbind.
#

case "$1" in
bind)
	FILE="$2"
	FLAGS="$3"

	# Store the list of available vnd(4) devices in ``available_disks'',
	# and mark them as ``free''.
	#
	list=`/bin/ls -1 /dev/vnd[0-9]*d | sed "s,/dev/vnd,,;s,d,," | sort -n`
	for i in $list; do
		disk="vnd$i"
		available_disks="$available_disks $disk"
		eval $disk=free
	done

	# Mark the used vnd(4) devices as ``used''.
	for disk in `sysctl hw.disknames`; do
		case $disk in
		vnd[0-9]*) eval $disk=used ;;
		esac
	done

	vnconfig_flags=
	case "$FLAGS" in
	*r*)	vnconfig_flags="$vnconfig_flags -r" ;;
	esac

	# Configure the first free vnd(4) device.
	for disk in $available_disks; do
		eval status=\$$disk
		vnconfig_cmd="vnconfig $vnconfig_flags /dev/${disk}d $FILE"
		if [ "$status" = "free" ] && \
		   eval $vnconfig_cmd >/dev/null; then
			echo /dev/${disk}d
			exit 0
		fi
	done
	exit 1
	;;

unbind)
	NODE="$2"
	vnconfig -u $NODE
	exit 0
	;;

*)
	echo "Unknown command: $1"
	echo "Valid commands are: bind, unbind"
	exit 1
	;;
esac
