#!/bin/sh

. /etc/autoconf.conf

MOUNT_DIR="/var/usbmount"

#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)
	
mount_partition()
{
	if [ "$1" != "" ]; then
		device="$1";
	else
		device="sda1";
	fi;
	
	scsi_info /dev/$device > /dev/null
	if [ $? = 0 ] && [ -z "$(grep $device /proc/mounts)" ]; then
		echo "Mounting device: $device"
		mkdir "$MOUNT_DIR/$device";
		mount "/dev/$device" "$MOUNT_DIR/$device" -o sync,noatime -o uid=$UID -o gid=$GID -o umask=000
		if [ $? != 0 ]; then
		    rmdir "$MOUNT_DIR/$device";
		else
		    echo "Mounted $MOUNT_DIR/$device"
		    if [ $firstdeviceset = "no" ]; then
			rm /dl/disk;
			ln -s $MOUNT_DIR/$device /dl/disk;
			firstdeviceset="yes";
			echo "$device set as main disk device";
		    fi
		fi
	fi
}

umount_partition()
{
	if [ "$1" != "" ]; then
		device="$1";
	else
		device="sda1";
	fi;
	grep $device /proc/mounts && umount "/dev/$device" && rmdir "$MOUNT_DIR/$device" && echo "Umounting device: $device"
}
mount_all()
{
        # wait the device to be ready
        sleep 3
	for disk in sda sda1 sda2 sda3 sda4 sda5 sda6 sda7 sda8 sda9 sdb1 sdb2 sdb3 sdb4 sdb5 sdb6 sdb7 sdb8 sdb9
	do
		mount_partition $disk
	done;
}

umount_all()
{
	for disk in sda sda1 sda2 sda3 sda4 sda5 sda6 sda7 sda8 sda9 sdb1 sdb2 sdb3 sdb4 sdb5 sdb6 sdb7 sdb8 sdb9
	do
		umount_partition $disk
	done;
}

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

	restart)
		echo "Restart usb storage\n"
		umount_all
		rmmod usb-storage
		insmod usb-storage
		mount_all 
		;;
    *)
        echo "do nothing"
        ;;

esac

