#!/bin/sh 
# This script for hotplug usb disk.
# Author Johnson. 2006/05/30

PATH=/sbin:/bin:/usr/sbin:/usr/bin

`/etc/qc/getqc`
isqc=`echo $?`
# Get jumpper Value
if [ $isqc -eq 0 ]; then
        exit 0;
fi

FAT32_ID1="kdosfs"
FAT32_ID2="SDOS5.0"
FAT32_ID3="FAT16"
NTFS_ID1="NTFS"
PART1=1
PART2=2
PART3=3

MOUNT_TREE=/web/raid/usbhdd

if [ ! -d $MOUNT_TREE ]; then
	mkdir -m 755 $MOUNT_TREE
fi

FOUND=0 # A flag to mark whether find device
/etc/qc/ledon 4 &
sleep 5

for device in /dev/sda /dev/sdb /dev/sdc /dev/sdd /dev/sde /dev/sdf
do
	for sub_device in $device$PART1 $device$PART2 $device$PART3
	do
		dd if=$sub_device of=/tmp/out.fat32 count=1 2>/dev/null
		if [ $? != 0 ]; then
			continue  
			# This sub_device does not exist.
		fi

	#	sleep 1
		mount | grep "$sub_device" 
		if [ $? = 0 ]; then
			continue 
			# This sub_device has been mounted.
		fi
	
		MOUNT_DIR=$MOUNT_TREE/$(basename $sub_device)

	
		if [ ! -d $MOUNT_DIR ]; then
			mkdir -p $MOUNT_DIR
		fi

		grep $FAT32_ID1 /tmp/out.fat32
		ret_val1=$?
		grep $FAT32_ID2 /tmp/out.fat32
		ret_val2=$?
		grep $FAT32_ID3 /tmp/out.fat32
		ret_val3=$?
		grep $NTFS_ID1 /tmp/out.fat32
		ret_val4=$?
	
		if [ $ret_val1 = 0 -o $ret_val2 = 0 -o $ret_val3 = 0 ]; then
       			mount -t vfat -o umask=0000,iocharset=utf8 $sub_device $MOUNT_DIR
		elif [ $ret_val4 = 0 ]; then
       			mount -t ntfs -o umask=0000,ro,nls=utf8 $sub_device $MOUNT_DIR
		else
              		mount -t auto $sub_device $MOUNT_DIR
		fi
		if [ $? != 0 ]; then
			/etc/qc/ledon 7 &
			rm -fr $MOUNT_DIR
		else
			FOUND=1
			touch $MOUNT_DIR
		fi

	done # sub_device


	if [ $FOUND = 1 ]; then 
		RMV_SHELL=/etc/hotplug/usb/$(basename $device).rmv
		echo "#!/bin/sh" > $RMV_SHELL
		echo "umount $MOUNT_TREE/$(basename $device)$PART1 >/dev/null 2>&1" >> $RMV_SHELL
		echo "umount $MOUNT_TREE/$(basename $device)$PART2 >/dev/null 2>&1" >> $RMV_SHELL
		echo "umount $MOUNT_TREE/$(basename $device)$PART3 >/dev/null 2>&1" >> $RMV_SHELL
		echo "rm -rf $MOUNT_TREE/$(basename $device)$PART1 >/dev/null 2>&1" >> $RMV_SHELL 
		echo "rm -rf $MOUNT_TREE/$(basename $device)$PART2 >/dev/null 2>&1" >> $RMV_SHELL 
		echo "rm -rf $MOUNT_TREE/$(basename $device)$PART3 >/dev/null 2>&1" >> $RMV_SHELL 

		ln -s $RMV_SHELL $REMOVER  2>/dev/null
		chmod a+x $RMV_SHELL $REMOVER

		break;
	fi
done

/etc/qc/ledoff 4
/etc/qc/ledoff 7
