#!/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
    MOUNTDIR="disk_$BLOCKDEV"
    MOUNTPOINT="/media/$MOUNTDIR"
    
    # 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
            
            #Default event handler interface
            if [ -z "$AUTORUNFILES" ]; then
              # App and Script Command filenames
              APPCOMMANDFILE=/app/event/app_command
              SCRIPTCOMMANDFILE=/app/event/script_command
              
              #Remount as read/write
              mount -o remount,rw ${MOUNTPOINT}
              echo -n ${MOUNTDIR} > /media/usbinfo.txt
              
              # Wait for USBSTICK_EJECT script command
              echo "Waiting command USBSTICK_EJECT..."
              while [ ! -f ${SCRIPTCOMMANDFILE} ]; do
                sleep 1
              done
              
              # Remove command file
              rm ${SCRIPTCOMMANDFILE}

              # Remount ourselves read only
              mount -o remount,ro ${MOUNTPOINT}

              # Get default app
              DEFAULTAPP=$(cat /app/data/config/defaultapp)

              # Send the USBSTICK_EJECTREADY event command
              echo "Sending command USBSTICK_EJECTREADY..."
              echo -n "USBSTICK_EJECTREADY" > $APPCOMMANDFILE
              killall -USR1 $DEFAULTAPP

              echo "Finsihed"
            fi
        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
