#! /bin/bash

usage ()
{
  echo "
Usage: `basename $1` --device <device>

Mandatory options:
  --device				SD block device node (e.g /dev/sdd)

Optional options:
  --rootfs <path/to/rootfs.tar.gz>	Use provided rootfs tarball
  --kernel <path/to/kernel.tar.gz>	Use provided kernel tarball
  --uboot <path/to/u-boot.tar.gz>	Use provided u-boot tarball
  --help				Print this help message.
"
  exit 1
}

BASE_DIR=$(dirname $0)
KERNEL_URL="https://copy.com/JNh9V08fl4AH17h4/us02-public/us02-kernel.tar.gz?download=1"
ROOTFS_URL="https://copy.com/JNh9V08fl4AH17h4/us02-public/core-image-sato-usom02.tar.gz?download=1"
UBOOT_URL="https://copy.com/JNh9V08fl4AH17h4/us02-public/us02-uboot.tar.gz?download=1"

# Process command line...
while [ $# -gt 0 ]; do
  case $1 in
    --help | -h)
      usage $0
      ;;
    --device) shift; device=$1; shift; ;;
    --kernel) shift; kernel=$1; shift; ;;
    --uboot) shift; uboot=$1; shift; ;;
    --rootfs) shift; rootfs=$1; shift; ;;
  esac
done

test -z $device && usage $0

if [ ! -b $device ]; then
   echo "ERROR: $device is not a block device file"
   exit 1;
fi

# Check privileges
if [ ! "$(whoami)" = "root" ]; then
   echo "ERROR: this script should be executed with root privileges"
   exit 1;
fi

mkdir -p "$BASE_DIR/files"

# Check necessary files
if [ -n "$kernel" ]; then
   [ ! -f "$kernel" ] && echo "ERROR: specified kernel tarball not found" && exit 1
else
   kernel="$BASE_DIR/files/us02-kernel.tar.gz"
   [ ! -f "$BASE_DIR/files/us02-kernel.tar.gz" ] && wget $KERNEL_URL -O $BASE_DIR/files/us02-kernel.tar.gz
fi

if [ -n "$uboot" ]; then
   [ ! -f "$uboot" ] && echo "ERROR: specified uboot tarball not found" && exit 1
else
   uboot="$BASE_DIR/files/us02-uboot.tar.gz"
   [ ! -f "$BASE_DIR/files/us02-uboot.tar.gz" ] && wget $UBOOT_URL -O $BASE_DIR/files/us02-uboot.tar.gz
fi

if [ -n "$rootfs" ]; then
   [ ! -f "$rootfs" ] && echo "ERROR: specified rootfs tarball not found" && exit 1
else
   rootfs="$BASE_DIR/files/core-image-sato-usom02.tar.gz"
   [ ! -f "$BASE_DIR/files/core-image-sato-usom02.tar.gz" ] && wget $ROOTFS_URL -O $BASE_DIR/files/core-image-sato-usom02.tar.gz
fi

echo "************************************************************"
echo "*         THIS WILL DELETE ALL THE DATA ON $device        *"
echo "*                                                          *"
echo "*         WARNING! Make sure your computer does not go     *"
echo "*                  in to idle mode while this script is    *"
echo "*                  running. The script will complete,      *"
echo "*                  but your SD card may be corrupted.      *"
echo "*                                                          *"
echo "*         Press <ENTER> to confirm....                     *"
echo "************************************************************"
read junk

for i in `ls -1 $device?`; do
 echo "Unmounting device '$i'"
 umount $i 2>/dev/null
done

# Get device total size in MB
totalSize=$(($(sfdisk -s $device )/1000))

# Default boot partition size in MB
bootSize=40

# Default uboot partition size in MB
ubootSize=$(( ($totalSize/100)*4 ))

# Erase partition table
dd if=/dev/zero of=$device bs=1M count=5
sync

# Get root partition size in MB
rootSize=$(( $totalSize - ($bootSize + $ubootSize) ))

# Create partiotions
echo "Creating partitions..."
sfdisk $device -D -uM << EOF
,$bootSize,b
,$rootSize
,,a2
;
EOF
sync

sfdisk $device --activate=$device 1

# Format partitions
echo "Formating BOOT partition..."
mkfs.vfat -F 32 -n "BOOT" ${device}1
sync
echo "Formating ROOT partition ..."
mkfs.ext3 -L "ROOT" ${device}2
sync

# Mount partitions
mkdir -p /media/mk_BOOT
mount ${device}1 /media/mk_BOOT
mkdir -p /media/mk_ROOT
mount ${device}2 /media/mk_ROOT

# Deploy files
echo "Copying files to SD..."
sudo tar xzf $kernel --no-same-owner -C /media/mk_BOOT
sudo tar xzf $rootfs -C /media/mk_ROOT
sync
tar xzf $uboot -C $BASE_DIR/files
sync
sleep 10
dd if=$BASE_DIR/files/u-boot.img of=${device}3 bs=64k seek=4
sync

umount -l ${device}1
umount -l ${device}2

rm -rf /media/mk_BOOT
rm -rf /media/mk_ROOT

echo "completed!"

