#!/bin/sh

. /etc/profile

USB_STORAGE=/proc/scsi/usb-storage-?/?
DRIVES="A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"

TAG=usb_mount

MNTPNT=/dev/shm/storage

LOGNAME="unknown"
export LOGNAME

find_hostnum()
{
	host=`cat $1 | grep Host | sed -e 's,^.*Host scsi\([[:digit:]]\).*$,\1,'`
	echo $host
}

find_attached() 
{
	for dev in $USB_STORAGE; do
		attached=`cat $dev | grep Attached | sed -e 's,^.*Attached: \(Yes\|No\).*$,\1,'`

		if [ "$attached" = "Yes" ]; then
			echo $dev
		fi
	done
}

find_detached() 
{
	for dev in $USB_STORAGE; do
		attached=`cat $dev | grep Attached | sed -e 's,^.*Attached: \(Yes\|No\).*$,\1,'`

		if [ "$attached" = "No" ]; then
			echo $dev
		fi
	done
}

find_mounted() 
{
        target=$1
        while read line
        do
                set -- $line
                mounted_on=$2
                if [ "$mounted_on" = "$target" ];then
                        return 1                # found
                fi
        done < /proc/mounts

        return 0
}

do_mount() 
{
	attached_hosts=`find_attached`
	filesys=vfat
	mntflags=noatime,sync,umask=002,gid=100,utf8,shortname=mixed
	drivenum=0

	for host in $attached_hosts; do

		hostnum=`find_hostnum $host`
		
		partitions=/dev/scsi/host$hostnum/bus0/target0/lun?/part?
		
		for device in $partitions; do
			set -- $DRIVES
			shift $drivenum
			let drivenum=$drivenum+1
					
			mntpnt=$MNTPNT/$1

			find_mounted $mntpnt
			if [ $? -gt 0 ]; then
				continue
			fi

			if [ ! -d $mntpnt ]; then
				mkdir $mntpnt
			fi
			
			mount -t $filesys $device $mntpnt -o $mntflags
		done
	done
	qcop "QPE/Application/afilebrowser" "syncWith(QString)" "$MNTPNT"
}

do_umount() 
{
	detached_hosts=`find_detached`
	drivenum=0

	for host in $detached_hosts; do

		hostnum=`find_hostnum $host`
		partitions=/dev/scsi/host$hostnum/bus0/target0/lun?/part?
		
		for device in $partitions; do
			set -- $DRIVES
			shift $drivenum
			let drivenum=$drivenum+1
			
			mntpnt=$MNTPNT/$1
			
			find_mounted $mntpnt
			if [ $? -eq 0 ]; then
				continue
			fi

			umount $mntpnt
			if [ $? -eq 0 ]; then
				rmdir $mntpnt
			fi
		done
		#qcop "QPE/System" "filesChanged(QString)" "$mntpnt"
	done
	qcop "QPE/System" "filesChanged(QString)" "*"
}

case $1 in

	start)
		do_mount
		;;

	stop)
		do_umount
		modprobe -r usb-storage
		;;
esac
