#!/bin/sh
#
# sdcontrol 1.0 2001/8/8 21:33:19 (Hideki Hayami)
#
# Initialize or shutdown a SD card device
#
# The first argument should be either 'insert' of 'eject'.
#
# 2004/11/13 edited by Charles Long
# 	Allows for mounting of partition 1 on /home

ACTION=$1
DEVICE1=/dev/mmcd/disc0/part1
DEVICE2=/dev/mmcd/disc0/part2
PARTITIONS=/proc/partitions
PARTITION1=mmcda1
PARTITION2=mmcda2
MOUNT_POINT1=/mnt/card/
MOUNT_POINT2=/home
STORAGE_PID_FILE=/var/run/usbdstorage.pid
STORAGE_PID=""
USB_STATUS=""
STORAGE_DEV=""

if [ -r $STORAGE_PID_FILE ]; then
        STORAGE_PID=`cat $STORAGE_PID_FILE`
        USB_STATUS=`cat /proc/usb-storage | grep "USB status" | cut -d : -f 2`
        STORAGE_DEV=`cat /etc/hotplug/usbdstorage.conf`
fi

case "$ACTION" in
'insert')
	if ! ( mount | grep -q $DEVICE1 ); then
        	if [ "$USB_STATUS" = "USB_CONNECT" ]; then
                	if [ "$STORAGE_DEV" = "$DEVICE1" ]; then
                        	if [ $STORAGE_PID ]; then
                                	kill -HUP "$STORAGE_PID"
                        	fi
                       		exit 0
                	fi
        	fi
        	mount $DEVICE1 $MOUNT_POINT1
        	if [ "$STORAGE_DEV" = "$DEVICE1" ]; then
                	if [ $STORAGE_PID ]; then
                        	kill -HUP "$STORAGE_PID"
                	fi
        	fi
	fi 
        if ( ( grep -q $PARTITION2 $PARTITIONS ) && ! ( mount | grep -q $DEVICE2 ) ); then
		mount $DEVICE2 $MOUNT_POINT2
	fi	
        ;;
'eject')
        if [ "$STORAGE_DEV" = "$DEVICE1" ]; then
                if [ $STORAGE_PID ]; then
                        kill -HUP "$STORAGE_PID"
                fi
        fi
        if ( ( mount | grep -q $DEVICE1 ) && ! ( fuser -sm $DEVICE1 ) ); then
                umount $MOUNT_POINT1
   	fi			
        if ( ( mount | grep -q $DEVICE2 ) && ! ( fuser -sm $DEVICE2 ) ); then
		umount $MOUNT_POINT2
        fi
        ;;
'compeject')
        if [ "$STORAGE_DEV" = "$DEVICE1" ]; then
                if [ $STORAGE_PID ]; then
                        kill -HUP "$STORAGE_PID"
                fi
        fi
        if ( mount | grep -q $DEVICE1 ); then
        	fuser -ksm $DEVICE1 
        	if ! ( umount $MOUNT_POINT1 ); then
                	usleep 500000
               		umount $MOUNT_POINT1
        	fi
	fi
        if ( mount | grep -q $DEVICE2 ); then
        	fuser -ksm $DEVICE2 
        	if ! ( umount $MOUNT_POINT2 ); then
        		usleep 500000
        		umount $MOUNT_POINT2
        	fi
        fi
        ;;
'change')
        $0 compeject
        $0 insert
        ;;
'*')
        exit 1
        ;;
esac

exit 0

