#! /bin/bash
#
USB_ROOT="/proc/bus/usb/001/001"

ACTION=$1
DEVICE=$2
MOUNT_POINT="/mnt/usb"
MOUNT_LIST="$MOUNT_POINT/usbmount.lst"

mount_dev() {
   if [ ! -e $MOUNT_POINT ] ; then
      mkdir -p $MOUNT_POINT
   fi

   USB_DEV=`ls /dev/sd??`
   USB_MOUNTS=`mount | grep "^/dev" | grep " $MOUNT_POINT" | cut -f 3 -d " "`
   for i in $USB_DEV ; do
      DEV=`echo ${i} | cut -f 3 -d "/"`
      if [ ! -e $MOUNT_POINT/$DEV ] ; then
          mkdir $MOUNT_POINT/$DEV
          mount ${i} $MOUNT_POINT/$DEV > /dev/null 2>&1
          echo "$DEVICE $MOUNT_POINT/$DEV/" > $MOUNT_LIST
          logger -s "$MOUNT_POINT/$DEV mounted"
      else
          logger -s "$MOUNT_POINT/$DEV already mounted"
      fi
   done
}

unmount_all() {
   USB_MOUNTS=`mount | grep "^/dev" | grep " $MOUNT_POINT" | cut -f 3 -d " "`
   echo "<$USB_MOUNTS>"
   for i in $USB_MOUNTS ; do
      umount -f ${i} > /dev/null 2>&1
      logger -s "${i} unmounted"
   done
   rmdir $MOUNT_POINT/sd??
   rm -f $MOUNT_POINT/*
}

unmount_dev() {
   MP=`grep $DEVICE $MOUNT_LIST | cut -f2 -d" "`
   if [ "$MP" != "" ] ; then
      umount -f $MP > /dev/null 2>&1
      rmdir $MP
      cat $MOUNT_LIST | sed "\%$MP%d" > $MOUNT_LIST
      logger -s "$MP unmounted"
   else
      logger -s "$DEVICE not mounted"
   fi

}

DEV_ID=`echo $DEVICE | cut -f6 -d"/"`
if [ "$DEV_ID" = "001" ] ; then
   if [ "$DEVICE" = "$USB_ROOT" ] ; then
      logger -s "unmount_all"
      unmount_all
   fi
else
   if [ "$ACTION" = "add" ] ; then
      logger -s "usbmount add <$DEVICE>"
      mount_dev
   elif [ "$ACTION" = "remove" ] ; then
      logger -s "usbmount remove <$DEVICE>"
      unmount_dev
   elif [ "$ACTION" = "remove_all" ] ; then
      logger -s "unmount_all"
      unmount_all
   elif [ "$ACTION" = "add_all" ] ; then
      logger -s "add_all"
      mount_dev
   else
      logger -s "usbmount unknown <$DEVICE>"
   fi
fi

