#!/bin/sh

FAT_TYPE="6"
NUM=0
SCBUS=`/sbin/camcontrol devlist -v | grep umass | cut -d\  -f 1 |  sed "s/[^0-9]//g"`
if [ "${SCBUS}" = "" ];
then
    echo "No useful bus found. Aborting."
    exit
fi

DEVICES=`/sbin/camcontrol devlist -v | grep "scbus$SCBUS" | grep "^<" | sed "s/.*scbus//g" | sed "s/\ target\ /:/g" | sed "s/\ lun\ /:/g" | cut -d\  -f 1`
if [ "${DEVICES}" = "" ];
then
    echo "No devices found. Aborting."
    exit
fi

for i in $DEVICES
do
    RESULT=`camcontrol tur $i`
    if [ "$RESULT" = "Unit is ready" ]; then
        DEVICE=`/sbin/camcontrol periphlist $i | grep ^da | cut -d: -f 1`
        COUPLE=`fdisk /dev/${DEVICE} | grep -B 1 sysid | paste - -`
        PART_ID=`echo $COUPLE | cut -d\  -f 5`
        PART_TYPE=`echo $COUPLE| cut -d\  -f 8`
        if [ "$PART_TYPE" = "6" ]; then
            #We found a FAT partition
            IS_MOUNTED=`mount -a | grep "usb.0"`
            if [ "${IS_MOUNTED}" = "" ];
            then
            	mount -t msdos /dev/${DEVICE}s${PART_ID} /mnt/usb.0 > /dev/null 2>&1
                 [ -e /mnt/usb.0/freesbie.tar.bz2 ] && tar jxvf /mnt/usb.0/freesbie_data.tar.bz2 -C /
            	umount /mnt/usb.0 > /dev/null 2>&1
            else
                [ -e /mnt/usb.0/freesbie_data.tar.bz2 ] && tar jxvf /mnt/usb.0/freesbie_data.tar.bz2 -C /
            fi
        fi
    fi
done
