#!/bin/ksh
#
# dolofi - create lofi filesystems, mount, and share
#

#
# this is the netgroup the filesystems will be shared to
# change as appropriate for you setup
#
NETGRP="unix_hosts"

function doUsage {
	echo "Usage: dolofi [ -u | -l ]"
	echo "       dolofi -u device"
	echo "       dolofi filename device"
}

case $# in
1)
case $1 in
-u)
	for lofifs in `/bin/df -k | /bin/grep lofi | /bin/awk '{print $NF}'`
	do
		unshare $lofifs
		umount $lofifs
		rmdir $lofifs
	done
	for lofidev in `/usr/sbin/lofiadm | /bin/grep '^/dev/lofi' | /bin/awk '{print $1}'`
	do
		lofiadm -d $lofidev
	done
	;;
-l)
	/usr/sbin/lofiadm
	/bin/df -k | /bin/egrep '(^Filesystem|lofi)'
	;;
*)
	doUsage
	exit 1
	;;
esac
	;;
2)
	printf ""
	;;
*)
	doUsage
	exit 1
	;;
esac

#
# at this point we have two arguments
#
case $1 in
-u)
	DEV_TO_USE="$2"
	echo clearing /dev/lofi/${DEV_TO_USE}
	if [ -r /dev/lofi/${DEV_TO_USE} ]; then
	    for lofifs in `/bin/df -k /dev/lofi/${DEV_TO_USE} | /bin/grep lofi | /bin/awk '{print $NF}'`
	    do
		unshare $lofifs
		umount $lofifs
		rmdir $lofifs
	    done
	    lofiadm -d /dev/lofi/${DEV_TO_USE}
	fi
	;;
-*)
	doUsage
	exit 1
	;;
*)
	FILE_TO_MOUNT="$1"
	DEV_TO_USE="$2"
	if [ ! -f $FILE_TO_MOUNT ]; then
		echo "Unable to find file $FILE_TO_MOUNT"
		doUsage
		exit 1
	fi
	case $FILE_TO_MOUNT in
/*)
	printf ""
	;;
*)
	echo "You must specify an absolute path"
	exit 1
	;;
	esac
#
# autodetect solaris boot slice, assuming I keep the standard
# convention
#
        FILESYS_TYPE="hsfs"
	case $FILE_TO_MOUNT in
*-v1-s1.iso)
	FILESYS_TYPE="ufs"
	;;
*-v1-s0.iso)
	FILESYS_TYPE="ufs"
	;;
*.miniroot)
	FILESYS_TYPE="ufs"
	;;
	esac
#
# this is the command
#
	echo mkdir /mnt$DEV_TO_USE
	echo /usr/sbin/lofiadm -a $FILE_TO_MOUNT /dev/lofi/$DEV_TO_USE
	echo mount -F ${FILESYS_TYPE} -o ro /dev/lofi/$DEV_TO_USE /mnt$DEV_TO_USE
	echo share -F nfs -o ro=${NETGRP},anon=0 /mnt$DEV_TO_USE
	mkdir /mnt$DEV_TO_USE
	/usr/sbin/lofiadm -a $FILE_TO_MOUNT /dev/lofi/$DEV_TO_USE
	mount -F ${FILESYS_TYPE} -o ro /dev/lofi/$DEV_TO_USE /mnt$DEV_TO_USE
	share -F nfs -o ro=${NETGRP},anon=0 /mnt$DEV_TO_USE
	;;
esac
