#!/bin/sh
#============================================================================#
# Unmount hotplug devices as normal user                                     #
#============================================================================#
# (C) Denis Smirnov <mithraen@freesource.info>          http://mithraen.ru/  #
#============================================================================#
#HMOUNT=/usr/bin/hmount
PMOUNT=/usr/bin/pmount
PUMOUNT=/usr/bin/pumount
UDISKSCTL=/usr/bin/udisksctl
FUSERMOUNT=/usr/bin/fusermount

if [ -z "$1" ]; then
    echo "Use: $0 <block device>"
    exit -1
fi

# If it is fuse mount point -- unmount it with fusermount -u
if [ -d "$1" ]; then
    D=`realpath "$1"`
    if cat /proc/mounts \
            | sed 's/^[^ ]* //' \
            | fgrep -q "$D fuse"; then
        fusermount -u "$D"
        exit $?
    fi
fi


#if [ -x $HMOUNT ]; then
#    $HMOUNT -u "$DEV"
#elif


if [ -d "$1" ]; then
 DEV=`mount  | grep $1  | cut -d' ' -f1`
else
    if [ ! -b "$1" ];then
	DEV="/dev/$1"
    else
	DEV="$1"
    fi
fi

if [ -x $PMOUNT ]; then
    $PUMOUNT "$DEV"
elif [ -x $UDISKSCTL ]; then
    # TODO: add unmount by mount point
    if [ -b "$DEV" ]; then
        rez=`$UDISKSCTL unmount -b "$DEV" 2>&1 | grep :`
        if [ ! -z "$rez"  ]; then
         echo -n " " ; echo "$rez" | cut -d':' -f1
         echo "$rez" | cut -d':' -f4
        else
         echo "Ok: umount "$DEV" "
        fi
    else
        echo "$1 is not block device"
        exit -1
    fi
else
    /bin/umount "$DEV"
fi
