#!/bin/sh
#============================================================================#
# Unmount hotplug devices as normal user                                     #
#============================================================================#
# (C) Denis Smirnov <mithraen@freesource.info>          http://mithraen.ru/  #
#============================================================================#

PMOUNT=/usr/bin/pmount
PUMOUNT=/usr/bin/pumount
UDISKSCTL=/usr/bin/udisksctl
FUSERMOUNT=/usr/bin/fusermount


if [  -b "$1" ]; then
 DEV="$1" 
else
  if [  -b /dev/"$1" ]; then
     DEV=/dev/"$1" 
  else 
    if [ -n "$1" ]; then
      D=`cat /proc/mounts | grep "$1" | cut -d' ' -f1`
      DEV="$D"
      M=`cat /proc/mounts | grep "$1" | cut -d' ' -f2`
      [ -z $M ] || mpoint=`realpath $M` 
    fi
  fi
fi




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 it is fuse mount point -- unmount it with fusermount -u
if [ -d "$mpoint" ]; then
    if cat /proc/mounts \
            | sed 's/^[^ ]* //' \
            | fgrep -q "$mpoint fuse"; then
        fusermount -u "$mpoint"
        exit $?
    fi
fi


if [ -n "$D" ]; then
  DEV=$D
  shift
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`
        rz=$?
        if [ "$rz" -eq 1 ]; then
         echo $rez
        else
         echo "Ok: umount "$DEV" "
        fi
    else
        echo "$DEV is not block device"
        exit -1
    fi
else
    /bin/umount "$M"
fi
