#!/bin/sh

# Copyright (C) 2005, Kay Sievers <kay.sievers@vrfy.org>
# Copyright (C) 2006, David Zeuthen <david@fubar.dk>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2.

# read parameters
# "lazy\tforce\n"
# Only allow ^a-zA-Z0-9_= in the string because otherwise someone may
# pass e.g. umask=0600,suid,dev or umask=`/bin/evil`

read GIVEN_UNMOUNTOPTIONS
GIVEN_UNMOUNTOPTIONS="`echo \"$GIVEN_UNMOUNTOPTIONS\" | tr -Cd \"a-zA-Z0-9_=[:space:]\"`"

if [ -z "$MOUNT_POINT" ]; then
    echo "org.freedesktop.Hal.Device.Volume.UnknownMountpoint" >&2
    echo "Missing mountpoint, cannot figure out where device is mounted." >&2
    exit 1
fi

if [ -n "$GIVEN_UNMOUNTOPTIONS" ]; then
    for OPTION in $GIVEN_UNMOUNTOPTIONS; do
	OPTION_WAS_OK="0"
	for VALID_OPTION in $HAL_PROP_VOLUME_UNMOUNT_VALID_OPTIONS; do
	    if [ "x$OPTION" = "x$VALID_OPTION" ]; then
		OPTION_WAS_OK="1"
		break
	    fi
	done

	if [ "$OPTION_WAS_OK" = "1" ]; then
		case "$OPTION" in
		    "lazy")
			UNMOUNTOPTIONS="$UNMOUNTOPTIONS -l"
			OPTION_WAS_OK="1"
			;;
		    "force")
			UNMOUNTOPTIONS="$UNMOUNTOPTIONS -f"
			OPTION_WAS_OK="1"
			;;
		    *)
			echo "org.freedesktop.Hal.Device.Volume.UnsupportedUnmountOption" >&2
			echo "The option '$OPTION' is not supported" >&2
			exit 1
		esac
	else
		echo "org.freedesktop.Hal.Device.Volume.InvalidUnmountOption" >&2
		echo "The option '$OPTION' is invalid" >&2
		exit 1
	fi
    done
fi

RESULT=$(umount $UNMOUNTOPTIONS "$MOUNT_POINT"  2>&1)
if [ $? -ne 0 ]; then
    case "$RESULT" in
	*busy*)
	    echo "org.freedesktop.Hal.Device.Volume.Busy" >&2
	    echo "Device is busy." >&2
	    ;;
	*"not mounted"*)
	    echo "org.freedesktop.Hal.Device.Volume.NotMounted" >&2
	    echo "Device is not mounted." >&2
	    ;;
	*)
	    echo "org.freedesktop.Hal.Device.Volume.UnknownFailure" >&2
	    echo "Unknown failure: $RESULT" >&2
    esac
    exit 1
fi

# remove directory only if HAL has created it
if [ -e "$MOUNT_POINT/.created-by-hal" ]; then
  rm -f "$MOUNT_POINT/.created-by-hal"
  rmdir "$MOUNT_POINT" 2>/dev/null || true
fi

hal-set-property --udi $UDI --key info.hal_mount.created_mount_point --remove > /dev/null 2>&1
hal-set-property --udi $UDI --key info.hal_mount.mounted_by_uid --remove > /dev/null 2>&1

exit 0
