#!/bin/sh

anti_brick_check()
{
    # Get the product id and serial from OTP
    PRODUCTID=$(printf "%d" $(cat /sys/fsl_otp/HW_OCOTP_GP1))
    
    # Get the software update targetNumber from the info.xml
    targetNumber=-1
    #read the info.xml if it exist (new firmwares)
    if [ -f ${MOUNTPOINT}/info.xml ]; then
    	targetNumber=$(xmllint --xpath "string(//softwareInfo/targetInfo/targetNumber)" $MOUNTPOINT/info.xml)
    else
    	#if no info.xml file, check if we have an "old" 5" firmware update
        if [ -f $MOUNTPOINT/firmware/768.dtbu ]; then
            targetNumber=768
        fi
    fi

    echo "Hotplug: Running on Product ${PRODUCTID}, firmware update target: ${targetNumber}"
    if [ ${PRODUCTID} -ne ${targetNumber} ]; then

	pkill SeakeeperGyro500
	sleep 1

	fbv -s 1 app/bin/recoveryIncompatibleFirmware.png
	echo ERROR DURING UPDATE, INCOMPATIBLE SOFTWARE!
	
	umount $MOUNTPOINT
    	rmdir $MOUNTPOINT

	sleep 10
    	echo "Rebooting...."
    	reboot 
	exit 300
    fi
}

# ENVVARS - ACTION DEVPATH SUBSYSTEM MAJOR MINOR DRIVER

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

# 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 if the software being install is compatible
	    anti_brick_check
	    #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
