#
# Functions for hotplugable block device
#					Shuu Yamaguchi <shuu@dotAster.com>
# $Id: block_functions,v 1.9 2004/04/11 03:21:16 shuu Exp shuu $
#
. ${MURASAKI_SCRIPT_DIR}/func_debug
. ${MURASAKI_SCRIPT_DIR}/func_sysfs
. ${MURASAKI_SCRIPT_DIR}/block_config

# SIZE: size of device
# PARENT_DIR: if a block device does not mean a whole device buf 
#	      a partition, this is sysfs dir of a whole device.
# PARENT_SIZE: size of whole device if exists
get_size() {
	read SIZE < ${SYSFS_DIR}${DEVPATH}/size
	LEN=`expr ${DEV} : '.*[1-9][0-9]*'`
	if [ $LEN -ne 0 ];then	# $DEV is child
		PARENT_DIR=`dirname ${SYSFS_DIR}${DEVPATH}`
		decho PARENT_DIR:$PARENT_DIR
		read PARENT_SIZE < ${PARENT_DIR}/size
		decho PARENT_SIZE:$PARENT_SIZE
		if [ $SIZE -gt $PARENT_SIZE ];then
			STATUS=1
		fi
	fi
}

# DEV: device name
# STATUS: 0: good !0: fail
initialize(){
	STATUS=0
	DEV=`basename $DEVPATH`
	decho DEV:$DEV
	if [ "$ACTION" != "add" ];then
		return
	fi
	get_sysfs
	decho SYSFS_DIR:$SYSFS_DIR

	# kernel bug?
	LEN=`expr ${DEV} : '.*[1-9][0-9]*'`
	if [ $LEN -eq 0 ];then	# $DEV is parent
		for f in 1 1 1 2 2
		do
			if [ ! -e ${SYSFS_DIR}${DEVPATH}/${DEV}[[:digit:]]* ];then
				sleep $f
				touch /dev/${DEV}
			fi
		done
		if [ -e ${SYSFS_DIR}${DEVPATH}/${DEV}[[:digit:]]* ];then
			STATUS=1
			return;
		fi
	fi

	get_size
	decho SIZE:$SIZE
}

# $DEV is mounted or not?
# return: $MOUNTED	0: not mounted	1: mounted
check_mount() {
	MOUNTED=0
	while read dev tmp
	do
		if [ "$dev" = "/dev/${DEV}" ];then
			MOUNTED=1;
			break;
		fi
	done < /etc/mtab
}

# mount onto apropriate mount point
bossy_mount() {
	TYPE=""
	while read dev mnt type tmp
	do
		if [ "$dev" = "/dev/${DEV}" ];then
			TYPE=$type
			MNT=$mnt
			break;
		fi
	done < /etc/fstab
	if [ "${TYPE}" = "" ];then
		TYPE="auto"
		MNT=${MOUNT_BASE}/${DEV}
		mkdir -p ${MNT}
	fi
	if [ "${DESKTOP}" = "on" ];then
		. ${MURASAKI_SCRIPT_DIR}/func_desktop
		desktop_start
		mount /dev/${DEV}
	else
		mount -t ${TYPE} /dev/${DEV} ${MNT}
	fi
}

bossy_umount() {
	check_mount
	if [ $MOUNTED -eq 1 ];then
		umount /dev/${DEV}
	fi

	if [ "${DESKTOP}" = "on" ];then
		. ${MURASAKI_SCRIPT_DIR}/func_desktop
		desktop_stop
	fi
}
