#	@(#)disklabel	1.4	/sccs/src/cmd/sadmin/shell/s.disklabel
#	Ask the user to insert a medium and verify it is present.
#	Write the label to the standard output if it is present.

#!	chmod +x ${file}

usage="Usage:  $0 [ -y | -n'drivename' | -q'question' ] parent-pid filename
-n'drivename'	Provide a name for the drive.
-q'question'	Provide alternative question.
-y		return the label without asking questions"
ndrive='diskette drive'
question=

case $# in
2 )
	;;
3 )
	case "$1" in
	-n?* )
		ndrive=`expr "$1" : '-n\(.*\)'`
		;;
	-q?* )
		question=`expr "$1" : '-q\(.*\)'`
		;;
	-y )
		getit=yes
		;;
	* )
		echo >&2 "${usage}"
		exit 1
	esac
	shift
	;;
4 )
	case "$1" in
	-n )
		ndrive=$2
		;;
	-q )
		question=$2
		;;
	* )
		echo >&2 "${usage}"
		exit 1
	esac
	shift
	shift
	;;
* )
	echo >&2 "${usage}"
	exit 1
esac
: ${question:="Insert the medium in the ${ndrive}.  Press <RETURN> when ready. [q]"}

pid=$1
ddrive=$2
case ${ddrive} in
/dev/r* )
	#  WARNING:  This depends on the common, but not universal, naming
	#  convenetion that all character and block special devices are under
	#  /dev and if /dev/THING is a block device then /dev/rTHING is the
	#  corresponding character (aka "raw") device.  Note that THING may
	#  have directories as part of the name.
	#	if ddrive is raw, bddrive == block device for a raw device
	bddrive=/dev/`expr ${ddrive} : '/dev/r\(.*\)'`
	;;
* )
	#	otherwise they are the same.
	bddrive=${ddrive}
esac

trap 'exit 1' 1 2
trap "kill ${pid};  exit 0" 15
flags="-qq -k$$"

mounted=`/etc/mount  |
	sed -n "\\;${bddrive};s;^\\([^ ]*\\) on ${bddrive} .*;\\1;p"`
if [ -n "${mounted}" ]
then
	echo >&2 "The ${ndrive} is already mounted as the ${mounted} file system.
This command cannot run with it mounted."
	if [ ${getit} ]
	then
		kill ${pid}
		exit 0
	fi
	if  checkyn ${flags} -H"
	The ${ndrive} is already in use; it has a medium in it that
	is mounted as a file system starting at the ${mounted} directory.
	Before you can use the ${ndrive} for some other purpose, you
	must unmount the medium now in use." \
		-f "Do you want to unmount it?"
	then
		if  diskumount ${bddrive} ${mounted}
		then
			:
		else
			echo >&2 "	This command cannot run because the ${mounted} file system is mounted.
	Unmount it and try again."
			kill ${pid}
			exit 0
		fi
	else
		echo >&2 "The medium in the ${ndrive} is still mounted on ${mounted}."
		kill ${pid}
		exit 0
	fi
fi

while true
do
	if [ -z "${getit}" ]
	then
		checklist ${flags} -f -D '' \
			"${question}" \
			'<RETURN>' ''
	fi
	label=`/etc/labelit ${ddrive} 2>/dev/null`
	if [ $? -eq 0 ]
	then
		break
	fi
		echo >&2 '
	The medium may not be properly inserted,
	the drive door may not be closed, the medium may not be formatted,
	the medium may be in upside-down, or there is some other problem.
	Check it and try again.
'
	if [ ${getit} ]
	then
		kill ${pid}
		exit 0
	fi
done
/etc/fsstat ${ddrive} >/dev/null 2>&1
if [ $? = 3 ]
then
	exit 0
fi
echo "${label}"