#!/bin/bash
#
# takes a device/partition and mounts it, read and writes to it, etc
# data-info  : give partition, return partition, mount-point,
# space available for testing

SLEEPDELAY=300

if [ -z "$2" ] ; then {
	echo "give me a device or NFS point and a size (can be 0 for full)"
	exit 2
} ; fi

device="$1"
size="$2"

# is the parameter an nfs specifier
echo $1 | grep -v ^/ | grep -q :/ >>/dev/null 2>&1
nfscheck=$?
# is the parameter a device specifier
echo $1 | grep -q ^/dev/ >>/dev/null 2>&1
devcheck=$?

if [ $nfscheck != 0 -a $devcheck != 0 ] ; then {
	# no need to mount -- we were given a directory specifier
	mpoint=$1
	if [ ! -d $1 ] ; then {
		echo invalid directory specification $1
		exit 2
	} ; fi
} ; else {

mkdir mountlock >>/dev/null 2>&1
while [ $? != 0 ] ; do
	sleep $[$RANDOM % 5]
	mkdir mountlock >>/dev/null 2>&1
done

# ok if it is mounted already it should be in /proc/mounts
mpoint=`mount | grep "$device " | head -n 1 | cut -f 3 -d ' '`

if [ ! -e "$mpoint" ] ; then {
	unset mpoint
	while [ -z "$mpoint" ] ; do {
		mpoint="/tmp/datamount.$RANDOM$RANDOM"
		mkdir $mpoint
		if [ $? != 0 ] ; then {
			unset mpoint
		} ; fi
	} done
	# try several methods
	mountok=0
	mount $device $mpoint >> /dev/null 2>&1
	if [ $? != 0 ] ; then {
		for i in `cat /proc/filesystems | grep -v nodev` ; do {
			mount -t $i $device $mpoint >> /dev/null 2>&1
			if [ $? = 0 ] ; then mountok=1 ; break ; fi
		} ; done
	} ; fi
} ; fi

rmdir mountlock

# ok if it is mounted already it should be in /proc/mounts
mpoint=`mount | grep "$device " | head -n 1 | cut -f 3 -d ' '`
if [ ! -e "$mpoint" ] ; then {
	echo error -- unable to mount $device >&2
	exit 2
} ; fi


} ; fi


if [ `basename $0` = "straverseread-info" ] ; then {
	sleep $[$RANDOM % $SLEEPDELAY]
} ; fi

echo $1 $size $mpoint 
