#!/bin/sh

# ENVVARS - ACTION DEVPATH SUBSYSTEM MAJOR MINOR DRIVER

# Redirect output
exec 1>/dev/ttyAMA0
exec 2>/dev/ttyAMA0

# Is it a disk device?
if [ "$SUBSYSTEM" == "block" -a "$MAJOR" ==  "8" ]; then
    # Get the devicename from the end of the device path
    BLOCKDEV=$(echo $DEVPATH | sed 's:.*/::g')

    # Create mountpoint name
    MOUNTPOINT="/media/disk_$BLOCKDEV"
    
    # Is it a device being added?
    if [ "$ACTION" == "add" ]; then
        # Yes, create mount point
        mkdir $MOUNTPOINT
        
        # Mount the device. Try up to 5 times
        TRIES=0        
        while [ $TRIES -lt 5 ]; do
            mount -t vfat -o ro /dev/$BLOCKDEV $MOUNTPOINT
            if [ $? -eq 0 ]; then
                break
            fi

            let TRIES++
                        
            if [ $TRIES -lt 5 ]; then
                # Delay for a second before next try
                sleep 1
            fi
        done

        if [ $TRIES -lt 5 ]; then
            # If we succeeded mounting, check for autorun files        
            echo "hotplug: Mounted $MOUNTPOINT, check for .ars files"
            AUTORUNFILES=$(ls $MOUNTPOINT/*.ars)
            for AUTORUNFILE in $AUTORUNFILES; do
                echo "hotplug: Autorunning file $AUTORUNFILE"
                /bin/sh $AUTORUNFILE
            done
        else
            # We failed to mount. Get rid of mount point
            rmdir $MOUNTPOINT
        fi
    elif [ "$ACTION" == "remove" ]; then
        # Device being removed, does mount point exist?
        if [ -d $MOUNTPOINT ]; then
            # Yes. Unmount and remove mount point
            umount $MOUNTPOINT
            rmdir $MOUNTPOINT
        fi
    fi
fi
