#!/bin/sh
#
# This is mount script for murasaki
# When you use this, you need to set up "/etc/murasaki/murasaki.mnttab"

MNTTAB=/etc/murasaki/murasaki.mnttab
TAG=murasaki_mount
SD="none sda sdb sdc sdd sde sdf sdg sdh"
SR="none sr0 sr1 sr2 sr3 sr4 sr4 sr5 sr6"
LOG_INFO="logger -i -t $TAG -p user.info"
LOG_ERR="logger -i -t $TAG -p user.err"
SCSI=/proc/scsi/scsi

# $1: device which need to be mounted
look_mounts() 
{
	target=$1
	while read line
	do
#		echo $line
		set -- $line
		mounted_dev=$1
		if [ $mounted_dev = $target ];then
			return 1		# found
		fi
	done < /proc/mounts

	return 0
}


# $1: pattern
# $2: partition 
find_dev()
{
	pattern=$1
	partition=$2
	grep $pattern $SCSI > /dev/null
	if [ $? -ne 0 ];then
#		$LOG_ERR "${pattern} was not found in $SCSI"
		exit 1
	fi
	NUM=`grep Vendor /proc/scsi/scsi | grep -n $pattern | sed -e 's/\([[:digit:]]*\):.*$/\1/'`

	set -- `grep 'Type:' /proc/scsi/scsi | sed -n ${NUM}p`
	TYPE=$2
	case $TYPE in
	"Direct-Access")
		set -- $SD
		shift $NUM
		device=/dev/$1
		if [ $partition -ne 0 ];then
			device=${device}${partition}
		fi
		;;
	"CD-ROM")
		set -- $SR
		shift $NUM
		device=/dev/$1
		;;
	*)
		$LOG_ERR "${device}:${pattern} is not mountable device"
		exit 1
		;;
	esac

	echo $device

	exit 0
}

do_mount() {
	grep -v '^#' $MNTTAB |
	while read line
	do
		set -- $line
		pattern=$1
		partition=$2
		mnt=$3
		fs=$4
#		echo "pattern:$pattern partition:$partition mnt:$mnt fs:$fs"
		device=`find_dev $pattern $partition`
		if [ $? -ne 0 ];then
			continue;
		fi
		look_mounts $device
		if [ $? -ne 0 ];then
			$LOG_INFO "$device has already mounted"
			exit 0
		fi
			
#		echo mount -t $fs $device $mnt
		mount -t $fs $device $mnt
		if [ $? -eq 0 ];then
			$LOG_INFO "${device} was mounted to $mnt"
		else
			$LOG_ERR "Error: ${device} was NOT mounted"
		fi
	done
}

case $1 in
start)
	do_mount
	;;
stop)
	# You have to run 'umount' by hand.
	;;
esac
