#!/bin/bash
#
# (c) Vector Linux, 2005
# Part of VL-Hot by Joe1962
# Licensed under the GPL v2
#
# vl-hot release 1.0.4
#


# Include configuration file:
. /etc/udev/vl-hot.conf

# Include support functions file:
. /lib/udev/vl-hot_functions


#**************************************************************************
# MAIN:
#**************************************************************************
feedback "Starting vl-hot_umount..."


if [ "$(id -un)" != "root" ]
then
	exec $SUDO $0 "$@"
	exit
fi

# Get device filename and volume number:
DEVNAME=$1
MOUNTBASE=${DEVNAME%%[0-9]*}
VOLNAME=vol${DEVNAME##[a-z]*[a-z]}


if [ $DIAG = "1" ]
then
	feedback "devname: $DEVNAME"
	feedback "mountbase: $MOUNTBASE"
	feedback "volname: $VOLNAME"
fi

MOUNTPOINT=$MOUNT_PATH/$MOUNTBASE/$VOLNAME
SOURCE=$2	# desktopicon, udev.
UMOUNTTYPE=$3

# Go unmount:
if [ $DIAG = "1" ]
then
	feedback $UMOUNTTYPE $MOUNTPOINT
fi

if [ $(mount | grep -c $MOUNTPOINT) = "0" ]
then
	feedback "$MOUNTPOINT not mounted, deleting $MOUNTPOINT and desktop icons"
	rmdir $MOUNTPOINT
	delDesktopIcon
else
	if [ $UMOUNTTYPE = "unmountsignal" ]
	then
		fuser -k -HUP -m $MOUNTPOINT
	elif [ $UMOUNTTYPE = "unmountkill" ]
	then
		fuser -k -KILL -m $MOUNTPOINT
	fi
	feedback "umounting $MOUNTPOINT"
	# Save cached data:
	sync
	# Unmounting:
	if umount $UMOUNT_OPTIONS $MOUNTPOINT
	then
		delDesktopIcon
		if [ $DIAG = "1" ]
		then
			feedback "removing $MOUNTPOINT"
		fi
		rmdir $MOUNTPOINT
		#if [ $SOURCE != "udev" ]
		if [ $SOURCE = "desktopicon" ]
		then
			NOT_CRIT="Normal"
			NOT_TIME="5000"
			NOT_CATG="device.removed"
			NOT_SUMM="VL-Hot unmount notification"
			NOT_MESS="$DEVNAME is now safely unmounted..."
			NOT_SND=$SND_SUCCESS
			fnotify
		fi
	else
		feedback "ERROR unmounting $MOUNTPOINT"
		if [ $SOURCE = "desktopicon" ]
		then
			NOT_CRIT="Critical"
			NOT_TIME="5000"
			NOT_CATG="device.error"
			NOT_SUMM="VL-Hot unmount notification"
			NOT_MESS="ERROR trying to unmount $MOUNTPOINT..."
			NOT_SND=$SND_ERROR
			fnotify
		fi
	fi
fi


# Check for empty drive mount dir and rm:
DRIVEDIR=$MOUNT_PATH/$MOUNTBASE
DIRSLEFT=$(ls $DRIVEDIR)
if [ -z "$DIRSLEFT" ]
then
	# No partition dirs left:
	if [ $DIAG = "1" ]
	then
		feedback "No partitions remaining, rmdir $DRIVEDIR/"
		rmdir $DRIVEDIR
	fi
else
	# There are partition dirs left:
	if [ $DIAG = "1" ]
	then
		feedback "Partitions remaining, no rmdir of $DRIVEDIR/"
	fi
fi

feedback "Finishing vl-umount..."
#**************************************************************************
