#!/bin/ksh

#
# iscdrom
#
iscdrom() {
	case "$1" in 
	*cdrom*)
		return 0
		;;
	""|*)
		return 1
		;;
	esac
}

#
# isslice2
#
isslice2() {

	case "$1" in 
	*-s2)
		return 0
		;;
	""|*)
		return 1
		;;
	esac
}

#
# issingle
#
issingle() {

	case "$1" in 
	*cdrom[0-9]|*cdrom[0-9][0-9]|*cdrom[0-9]-[0-9]*|*cdrom[0-9][0-9]-[0-9]*)
		return 0
		;;
	""|*)
		return 1
		;;
	esac
}

#
# usage
#
usage() {
	echo    "$1: check for media and open media found"
	echo    "Usage: $1 [-z nsecs][-fdD] [media_spec [cmd [arg ...]]]"
	echo    "  media_spec	floppy0, cdrom, *, etc. default: floppy"
	echo    "  cmd arg ...	command to run. default: dtaction Open"
	echo    "  -d		monitor continuously"
	echo    "  -z nsecs	sleep nsecs before doing anything"
	echo    "  -D		pass mount point AND device path to command"
	echo    "  -f		do not format any uninitialized floppies found"
	echo    "  -s		only match first matching medium in media_spec"
}

#
# cleanup - Call me before exiting
#
trap cleanup EXIT
cleanup() {
	if [[ -n "$eventWatcher" ]]; then kill $eventWatcher; fi
	if [[ -p "$fifo" ]]; then /bin/rm -f "$fifo"; fi
	if [[ -f "$lastCheck" ]]; then /bin/rm -f "$lastCheck"; fi
	if [[ -f "$lockFile" ]]; then /bin/rm -f "$lockFile"; fi
}

#
# OpenMedia mediaSpec [cmd [arg ...]]
#
# Does nothing if /tmp/sdtvolchecking_manually exists.
#
# $lastCheck		if set: only open volumes inserted since
#			mtime of $lastCheck
# $passDevice		see usage
# $formatFloppies	see usage
# $daemonMode		if false, wait for open command
#

#---------------------------------------------------------------------------
# Expand comma separated list of media specs into a space separated list
# containing full pathnames
#---------------------------------------------------------------------------
function ExpandMediaSpec {

        $(type nawk > /dev/null 2>&1)
        if [[ $? != 0 ]] then
                AWK="awk"
        else
                AWK="nawk"
        fi

        echo $1 | $AWK -F, '
                {ORS = " " }
                { for (i = 1; i <= NF; ++i) print "/tmp/.removable/"$i"*" }
'
}

OpenMedia() {
	_mediaSpec="$1"
	shift
	if [[ -f /tmp/sdtvolchecking_manually ]]; then
		return;
	fi
	
	#
	# wail for volmgt to create notification files after
	# the previous command
	#
	
	if [[ ! -n "$daemonMode" ]]; then
		for volumefile in $(ExpandMediaSpec $_mediaSpec); do	
			count=0
			while [[ ! -n "`ls -1 $volumefile 2>/dev/null`" \
				&& $count -lt 10 ]]; do
				ls -1 $volumefile
				count=$(( $count+1 ))
				sleep 1
			done	
		done
	fi
	
	if [[ $sleepTime = 0 ]]; then
		sleep 3
	else
		sleep $sleepTime
	fi
	
	for volumefile in $(ExpandMediaSpec $_mediaSpec); do	
		if [[ ! -f "$volumefile" ]]; then
			continue;
		fi
		if [[   -n "$lastCheck" \
		     &&  ("$volumefile" -ot "$lastCheck") ]]
		then
			continue;
		fi
		#
		# This would not handle spaces in volume names!
		# read mountPt devicePath < "$volumefile"
		#
		volumeSpec="`head \"$volumefile\"`"
		#
		# volumeSpec format: mountPt /some_volmgt_path
		# Assume the " " in " /" separates the 2 fields in volumeSpec
		#
		# Trim out " /" and everything following it
		mountPt="${volumeSpec% /*}"
		#
		# Trim out " /" and everything before it; prepend trimmed "/"
		devicePath=/"${volumeSpec#* /}"
                # remove the file system type field
                devicePath="${devicePath%% *}"
		uninitialized=
		protected=
		backup_slice=
		audio_only=
		if [[ "$mountPt" != /* ]]
		then
			if [[ "$mountPt" == "password_protected" ]]
 			then
			   protected=1
			   # use any mount point ???
			   mountPt=/floppy/$mountPt
			elif [[ "$mountPt" == "audio_only" ]]
			then
			   audio_only=1
			elif [[ "$mountPt" == "backup_slice" ]]
			then
			   backup_slice=1
			else
			   uninitialized=1
 			fi

		fi
		# Run in the background, so we can process next volume
		( \
			if [[ -n "$backup_slice" || -n "$audio_only" ]]; then \
                                true      ;\ 
                        else \
                            if [[ -n "$formatFloppies" && -n "$uninitialized" ]]; then \
                            	    if iscdrom "$volumefile"; then \
                            	    	true; \
                            	    else \
                                        if sdtmedia_format \
                                            -d "$devicePath" \
                                            -m "$mountPt"; \
                                        then \
                                            OpenMedia `basename $volumefile` $*; \
                                        fi; \
                                    fi; \
                            else \
                              if [[ -n "$protected" ]]; then \
                                    if sdtmedia_prot "$devicePath"; \
                                    then \
                                            OpenMedia `basename $volumefile` $*; \
                                    fi \
                              else \
                                    if [[ -x $mountPt/volstart ]];then \
                                            exec $mountPt/volstart; \
                                    else \
					    if iscdrom "$volumefile"; then \
						if isslice2 "$volumefile"; then \
						    DummymountPt="${mountPt%/s2*}"; \
						    exec ${*:-dtaction Open} "$DummymountPt" \
							    ${passDevice:+$devicePath}; \
						else \
							if issingle "$volumefile"; then \
								exec ${*:-dtaction Open} "$mountPt" \
									${passDevice:+$devicePath}; \
							fi \
						fi \
					    else \
						    exec ${*:-dtaction Open} "$mountPt" \
							    ${passDevice:+$devicePath}; \
					    fi \
                                    fi \
                              fi \
                            fi \
                         fi \
		) &
		if [[ ! -n "$daemonMode" ]]; then
			wait $!
		fi
                if [[ -n "$singleShot" ]]; then
                        break 
                fi

	done
}

#
# Main
#
cmd=`basename $0`
mediaSpec=floppy
daemonMode=
formatFloppies=1
passDevice=
fifo=
sleepTime=0
singleShot=

#
# Parse command line
#
while getopts h?xdsz:Df option
do
	case $option in
		h | \?)		usage $cmd; exit 1;;
		x)		set -x;;
		f)		formatFloppies=;;
		D)		passDevice=1;;
		d)		daemonMode=1;;
		z)		sleepTime=$OPTARG;;
                s)		singleShot=1;;
	esac
done

#
# Discard args processed by getopts
#
shift `expr $OPTIND - 1`

if [[ $# -gt 0 ]]; then
	mediaSpec="$1"
	shift
fi

sleep $sleepTime

if [[ ! -n "$daemonMode" ]]; then
	lockFile=/tmp/sdtvolchecking_manually
	/bin/touch $lockFile
	/bin/volcheck
	/bin/rm -f $lockFile
	OpenMedia $mediaSpec ${1+"$@"}
	exit 0
fi

if [[ ! -d /tmp/.removable ]]; then
	if mkdir /tmp/.removable; then :; else exit 2; fi
	if chmod 0777 /tmp/.removable; then :; else exit 2; fi
fi

if mkfifo /tmp/.removable/notify$$; then :; else exit 3; fi
fifo=/tmp/.removable/notify$$

lastCheck=/tmp/sdtvolcheck$$
/bin/touch 0101000070 $lastCheck

while true; do
        if [ -z "`/bin/ls -1 /tmp/fmt_in_progress_* 2>/dev/null`" ]; then
            OpenMedia "$mediaSpec" ${1+"$@"}
        fi
	/bin/touch $lastCheck
	/bin/cat $fifo >/dev/null &
	eventWatcher=$!
	wait $!
	if [[ ! -a "$fifo" ]]; then
		if mkfifo "$fifo"; then :; else exit 3; fi
	fi
done

exit 0
