#! /bin/sh

#######################################
# Check input parameters
#######################################

SDCARD_DEV=$1

# Simplify the device to its minimal expression
SDCARD_DEV="$(dirname $SDCARD_DEV)/$(basename $SDCARD_DEV)"

if [ -z $SDCARD_DEV ]; then
	echo "\ERROR: Must set the destination device\n"
	echo "Syntax:  $0 [device]"
	echo "Example: $0 /dev/sdg\n"
	exit 1
fi

# Make sure we are not trying to write to the primary partition
if [ $SDCARD_DEV = "/dev/sda" ]; then
	echo "\nERROR: Forbidden to write to /dev/sda\n"
	echo "Syntax:  $0 [device]"
	echo "Example: $0 /dev/sdg\n"
	exit 1
fi

# Check that we are writing to a block device
if [ ! -b $SDCARD_DEV ]; then
	echo "\nERROR: $SDCARD_DEV is not a block device\n"
	exit 1
fi


#######################################
# Copy the bootloader
#######################################

BOOTLOADER_IMG=barebox.bin

echo "Copying barebox..."
sudo dd if=$BOOTLOADER_IMG of=$SDCARD_DEV bs=512 || exit 1
sync


#######################################
# Copy the kernel
#######################################

KERNEL_IMG=uImage.sec

echo "Copying kernel..."
sudo dd if=$KERNEL_IMG of=$SDCARD_DEV bs=512 seek=1024 || exit 1
sync


#######################################
# Create Partition Table
#######################################

# Unmount everyone
sudo umount ${SDCARD_DEV}*

# Check if the device name is mmcblkX
if echo "${SDCARD_DEV}" | grep -q mmcblk; then
	PART_NAME=${SDCARD_DEV}p1
else
	PART_NAME=${SDCARD_DEV}1
fi

SIZE=`sudo fdisk -l ${SDCARD_DEV} | grep Disk | awk '{print $5}'`
CYLINDERS=`echo $SIZE/8225280 | bc`

if [ $CYLINDERS -eq 0 ]; then
	echo "\nERROR: 0 cylinders\n"
	exit 1
fi

echo "DISK SIZE - $SIZE bytes"
echo "CYLINDERS - $CYLINDERS"

# Create a single ext3 partition while leaving space for U-Boot and kernel
{
echo 4,,,*
} | sudo sfdisk -H 255 -S 63 -C $CYLINDERS ${SDCARD_DEV}

echo "Copying rootfs..."
dd if=rootfs.squashfs of=${SDCARD_DEV}1

sync && sync

