#!/bin/sh

. /etc/autoconf.conf

MOUNT_DIR="/var/usbmount"
USBDEVPATH="/dev/scsi"	
LOGFILE="/var/log/usbstorage.log"


#we want to store the location of the first partition that is succesfully mounted in a config file
firstdeviceset="no"

# look for nobody UID and GID
UID=$(id -u nobody)
GID=$(id -g nobody)
	

# The DEVINFO has host, bus, target and lun info
# DEVPATH has "/class/scsi_device/h:b:t:l"
# We could find the real device path with it

	
mount_partition()
{
  #we mount all parttition already found
  if [ "$1" != "" ]; then
		device="$1";
	else
		exit;
	fi;
	
  scsi_info $device > /dev/null
	if [ $? = 0 ] && [ -z "$(grep $device /proc/mounts)" ]; then

	  #we search a mout point to create
	  IND=1
	  while [ -e  ${MOUNT_DIR}/disk$IND ] ; do
	    IND=`expr $IND + 1`
	  done
	  MOUNT_PATH=${MOUNT_DIR}/disk$IND
	  mkdir $MOUNT_PATH

	  mount $device $MOUNT_PATH 1>/dev/null 2>/dev/null 
	  if [ $? -ne 0 ] ; then 
	    #Remove directory on failed mount
	    echo "Failed to mount $MOUNT_PATH" >> $LOGFILE
	    rm -r $MOUNT_PATH
	  else
		  echo "Mounted $MOUNT_PATH" >> $LOGFILE
		  if [ $firstdeviceset = "no" ]; then
			  rm /dl/disk;
			  ln -s $MOUNT_PATH /dl/disk;
			  firstdeviceset="yes";
			  echo "$device set as main disk device" >> $LOGFILE;
		  fi
	  fi
  fi
}

umount_partition()
{
	if [ "$1" != "" ]; then
		device="$1";
	else
		exit;
	fi;
	grep $device /proc/mounts && umount $device
}

mount_all()
{
   # wait the device to be ready
   sleep 5
   for disk in `find $USBDEVPATH -name 'disc' 2>/dev/null` ; do
            disk2=""
            for disk2 in `find $(echo $disk|sed -e "s|disc||") -name 'part*' 2>/dev/null` ; do
                mount_partition $disk2
            done 
            if [ "$disk2" = "" ]; then
                mount_partition $disk
            fi
   done
}

umount_all()
{
 for disk in `mount |grep $MOUNT_DIR|cut -f1 -d' '` ; do
        ls $disk > /dev/null 2>&1
        if [ $? != 0 ]; then
            disk=$(mount |grep $disk|cut -f3 -d' ')
            umount_partition $disk
            rm -r $disk
            echo "the device $disk is umounted" >> $LOGFILE
        fi
  done
}


case $1 in
	start)
		echo "Mounting USB device"  >> $LOGFILE
		modprobe fat
		modprobe vfat
		[ ! -d $MOUNT_DIR ] && mkdir $MOUNT_DIR
	  ##cold plug
		[ ! -z "$CONFIG_USBMGR" ] && mount_all
        ;;
    mount_all)
      echo "mount_all"  >> $LOGFILE
    	mount_all
		;;
    mount)
    echo "mount $2"  >> $LOGFILE
		mount_partition $2
		;;
    umount)
      echo "umount $2"  >> $LOGFILE
    	umount_partition $2
		;;
    umount_all)
    echo "umount_all"  >> $LOGFILE
		umount_all  
		;;
    stop)
		$0 umount_all
		rmmod vfat
		rmmod fat
        ;;

	restart)
		echo "Restart"  >> $LOGFILE
		umount_all
		;;
    *)
      echo "do nothing"
    ;;

esac

