#!/bin/bash
# /usr/local/bin/askmount
# udev RUN script for displaying a mount dialog,
# mount device if requested.
# (C) Klaus Knopper 2011
# License: GPL V2

# $DEVNAME (absolute device path), $ID_MODEL (product name)
# and $ID_FS_TYPE (file system type) are environment variables
# exported by udev.

[ -n "$DEVNAME" ] || DEVNAME="$1"

if [ -z "$DEVNAME" ]; then
 echo "$0 must be called with partition as argument, exiting." >&2
 exit 1
fi

# Get access to the first display running X

export DISPLAY=":0"
export XAUTHORITY="$(ps f -C xinit -C Xorg -C X | \
                     sed -n 's/.*-auth \(.*\)/\1/p' | head -1)"

# Check if we have $XAUTHORITY before continuing.
if [ ! -r "$XAUTHORITY" ]; then
 echo "No access to local display, exiting." >&2
 exit 1
fi

# Now, ask user for permission to mount device.

if zenity --question --title="New device detected"  \
          --text="$ID_MODEL\n
Would you like to mount $DEVNAME?" ; then

  # Create mountpoint, replacing /dev/ by /media/ in $DEVNAME
  mountpoint="${DEVNAME/\/dev\///media/}"
  mkdir -p "$mountpoint"

  # Everyone should be able to umount the device later.
  options="users"

  # If file system type does not support permissions,
  # set default to read/write for everyone.
  case "$ID_FS_TYPE" in
    *fat|msdos|ntfs) options="$options,umask=000" ;;
  esac

  # Do the mount, and inform the user about success/failure.
  if mount -o "$options" "$DEVNAME" "$mountpoint"; then
    zenity  --info --timeout=5 --title="Device mounted" \
            --text="Done.\n
You can now access the device at $mountpoint.\n
Please don't forget to umount before unplugging the device."
  else
    zenity  --error --timeout=5 --title="Error" \
            --text="Sorry, could not mount $DEVNAME."
  fi
fi
