#!/bin/sh

# USB removable device mount/unmount via udev, borrowing a lot of code from
# usbmount

# This script uses a number of environment variables starting with "$ID_..."
# set by udev  to find out things about the device.

# Escape from systemd to avoid getting  killed prematurely:
if [ -d /sys/fs/cgroup/systemd ]; then
    echo $$ > /sys/fs/cgroup/systemd/tasks
fi

# Don't try to automount cards; udev notices them only once they are mounted
# manually
echo $ID_MODEL | grep -qi IC1210 && exit 0
echo $ID_MODEL | grep -q Reader && exit 0
echo $ID_MODEL | grep -q CRW && exit 0

name=`echo $ID_VENDOR $ID_MODEL | tr [:upper:] [:lower:] | tr -c '[a-z0-9.\n]' _`
: ${name:=removable}

if [ "$ACTION" = "add" ]; then

  test -n "$ID_FS_TYPE" || exit 0
  test "$ID_FS_TYPE" != "swap" || exit 0

  read_success=
  for t in 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19; do
    if dd if="$DEVNAME" of=/dev/null bs=512 count=1; then
      read_success=yes
      break
    fi
    sleep 1
  done
  test -n "$read_success" || exit 1

  # set extra options for vfat and ntfs
  opts="nodev,noatime"
  if [ "$ID_FS_TYPE" = "vfat" -o "$ID_FS_TYPE" = "ntfs" ]; then
    opts="$opts,noexec,gid=storage,dmask=0007,fmask=0117"
  fi

  if [ -d /tmp/mountsrv ]; then
    echo $name "-t$ID_FS_TYPE" "${opts:+-o$opts}" "$DEVNAME" > /tmp/mountsrv/$$
  else

    # remove stale mountpoints in case the device has been unmounted manually or
    # during system shutdown
    for m in /media/${name}_? ; do
      grep -q $m /proc/mounts || rmdir $m
    done

    # try to create mount point, allowing up to 10 devices of the same model
    mntpt=
    for n in 0 1 2 3 4 5 6 7 8 9 ; do
      if mkdir "/media/${name}_$n" ; then
        mntpt="/media/${name}_$n"
        break;
      fi
    done
    test -n "$mntpt" || exit 1

    mount "-t$ID_FS_TYPE" "${opts:+-o$opts}" "$DEVNAME" "$mntpt" || { rmdir "$mntpt"; exit 1; } &
  fi

elif [ "$ACTION" = "remove" ]; then

  mntpt=`grep "$DEVNAME" /proc/mounts | cut -d' ' -f2 | grep $name`
  # grep $name shouldn't be necessary, just to be safe...

  if [ -n "$mntpt" ]; then

    umount -l "$mntpt"

    rmdir "$mntpt"

  fi

  # remove stale mountpoints in case the device has been unmounted manually
  for m in /media/${name}_? ; do
    grep -q $m /proc/mounts || rmdir $m
  done

fi

exit 0

