#!/bin/sh
# Script used by kdesktop to eject a removable media (CDROM/Tape/SCSI/Floppy)
# Relies on the 'eject' program, 'cdcontrol' on *BSD
#
# Copyright GPL v2 by David Faure <david@mandrakesoft.com>
#

fatal_error() {
	kdialog --title "KDE Eject" --error "$1"
	exit 1
}

error() {
	kdialog --title "KDE Eject" --error "$1"
}

eject_fallback() {
  # Checking for stuff in the PATH is ugly with sh.
  # I guess this is the reason for making this a kde app...
  OS=`uname -s`
  case "$OS" in
    OpenBSD)
      cdio -f $1 eject >/dev/null 2>&1
      ;;
    *BSD)
      dev=`echo $1 | sed -E -e 's#/dev/##' -e 's/([0-9])./\1/'`
      cdcontrol -f $dev eject >/dev/null 2>&1
      ;;
		*)
			eject $1 >/dev/null 2>&1
			;;
  esac
}

quiet=0
if test "$1" = "-q"; then
  quiet=1
  shift
fi

if test "$1" = "--help"; then
  "Usage: $0 <name> where name is a device or a mountpoint."
   exit 0
fi

if test -z "$1"; then
  for dev in /dev/cdrom /dev/dvd /dev/dvdram /dev/cdrecorder; do
     if test -e $dev; then
        lp=`readlink $dev`
	if test -n "$lp"; then
	    device=/dev/$lp
	else
	    device=$dev
        fi
        break
    fi
  done
else
  device=$1
fi

# check if HAL userland tools are installed
if test -x `which hal-find-by-property`; then
	HAL_major=`hal-find-by-property --version | cut -d " " -f 2 | cut -d. -f1`
	HAL_minor=`hal-find-by-property --version | cut -d " " -f 2 | cut -d. -f2`
  # HAL umount and eject method exist only for HAL >= 0.5
	if test $HAL_major -eq 0 -a  $HAL_minor -ge 5 -o $HAL_major -gt 0;  then
	  # Try to find the UDi from the device name
		BLOCK_UDI=$(hal-find-by-property --key block.device --string "$1" | head -1)
		[ -n "$BLOCK_UDI" ] || fatal_error "Can't find UDI for URL $1"
		STORAGE_UDI=$(hal-get-property --udi $BLOCK_UDI --key block.storage_device)
		[ -n "$STORAGE_UDI" ] || fatal_error "Can't find device for volume $BLOCK_UDI"
		
	  # Unmount each device volume
		for VOLUME_UDI in $(hal-find-by-property --key block.storage_device --string $STORAGE_UDI); do
			[ $(hal-get-property --udi $VOLUME_UDI --key block.is_volume) = true ] || continue
			[ $(hal-get-property --udi $VOLUME_UDI --key volume.is_mounted) = true ] || continue
			ERROR=$(dcop kded mediamanager unmount $VOLUME_UDI)
			[ -n "$ERROR" ] && error "$ERROR"
 		done
		[ $(hal-get-property --udi $VOLUME_UDI --key storage.requires_eject) = true ] &&
  		dbus-send --system --dest=org.freedesktop.Hal "$BLOCK_UDI" org.freedesktop.Hal.Device.Volume.Eject array:string:"" >/dev/null 2>&1
	else
    # fallback to the old eject method
		eject_fallback
	fi
else
  # fallback to the old eject method
  eject_fallback
fi

# refresh icons if media eject succeeded
if test $? -eq 0; then
  dcop kdesktop default refreshIcons
elif test $quiet -eq 0; then
  fatal_error "Eject $1 failed!"
fi

exit 0
