#!/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'.
#

ACTION=$1
DEVICE=/dev/mmcd/disc0/part1
MOUNT_POINT=/mnt/card
#FSTYPE="-t vfat"
#FATOPTS="-o noatime,quiet,umask=000,iocharset=utf8"
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')
	MOUNT_RES=`mount | grep $DEVICE`
	if [ ! "$MOUNT_RES" = "" ]; then
		exit 0
	fi
        if [ "$USB_STATUS" = "USB_CONNECT" ]; then
                if [ "$STORAGE_DEV" = "$DEVICE" ]; then
                        if [ $STORAGE_PID ]; then
                                kill -HUP "$STORAGE_PID"
                        fi
                        exit 0
                fi
        fi
        mount $FSTYPE $FATOPTS $DEVICE $MOUNT_POINT
	MOUNT_RES=`mount | grep $DEVICE`
	if [ "$MOUNT_RES" = "" ]; then
	        mount $FSTYPE $DEVICE $MOUNT_POINT
	fi
        if [ "$STORAGE_DEV" = "$DEVICE" ]; then
                if [ $STORAGE_PID ]; then
                        kill -HUP "$STORAGE_PID"
                fi
        fi
	if [ -f /usr/bin/ipkg-link ]; then
	    /usr/bin/ipkg-link mount $MOUNT_POINT
	fi
        ;;
'eject')
        if [ "$STORAGE_DEV" = "$DEVICE" ]; then
                if [ $STORAGE_PID ]; then
                        kill -HUP "$STORAGE_PID"
                fi
        fi
        fuser -s -m $DEVICE
        if [ $? = 1 ]; then
    		is_mount=`mount | fgrep $DEVICE`
    		if [ "$is_mount" = "" ]; then
            	    exit 0
		else
            	    umount $MOUNT_POINT
    		fi
	else
		exit 1
        fi
        ;;
'compeject')
        if [ "$STORAGE_DEV" = "$DEVICE" ]; then
                if [ $STORAGE_PID ]; then
                        kill -HUP "$STORAGE_PID"
                fi
        fi
        is_mount=`mount | fgrep $DEVICE`
        if [ "$is_mount" = "" ]; then
                exit 0
        fi
        fuser -k -m $DEVICE > /dev/null
        umount $MOUNT_POINT
        if [ $? != 0 ]; then
                usleep 500000
                umount $MOUNT_POINT
        fi
        ;;
'change')
        $0 compeject
        $0 insert
        ;;
'*')
        exit 1
        ;;
esac

exit 0

