#! /bin/bash

# mkSDTool v2.0

set -e

usage ()
{
  echo "
Usage: `basename $1` --machine [us01-x11|us01-wayland|us02|us03] --device <device>

Mandatory options:
  --device				SD block device node (e.g /dev/sdd)
  --machine				Machine [us01-x11,us01-wayland,us02,us03]

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
  --xloader <path/to/xloader.tar.gz>	Use provided u-boot tarball
  --help				Print this help message.
"
}

BASE_DIR=$(dirname $0)

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

[ -z "$device" -o -z "$machine" ] && usage $0 && exit 1

case "$machine" in
"us01-x11")
   KERNEL_URL="http://download.exorembedded.net:8080/Public/usom01/kernel/us01-kit-kernel-v2.0.tar.gz"
   ROOTFS_URL="http://download.exorembedded.net:8080/Public/usom01/rootfs/core-image-exor-x11-us01-kit-v2.0.tar.gz"
   UBOOT_URL="http://download.exorembedded.net:8080/Public/usom01/bootloader/us01-kit-uboot-v2.0.tar.gz"
   XLOADER_URL="http://download.exorembedded.net:8080/Public/usom01/xloader/us01-kit-xloader-v2.0.tar.gz"
   ;;
"us01-wayland")
   KERNEL_URL="http://download.exorembedded.net:8080/Public/usom01/kernel/us01-kit-kernel-v2.0.tar.gz"
   ROOTFS_URL="http://download.exorembedded.net:8080/Public/usom01/rootfs/core-image-exor-wayland-us01-kit-v2.0.tar.gz"
   UBOOT_URL="http://download.exorembedded.net:8080/Public/usom01/bootloader/us01-kit-uboot-v2.0.tar.gz"
   XLOADER_URL="http://download.exorembedded.net:8080/Public/usom01/xloader/us01-kit-xloader-v2.0.tar.gz"
   ;;
"us02")
   KERNEL_URL="http://download.exorembedded.net:8080/Public/usom02/kernel/us02-kit-kernel-v2.0.tar.gz"
   ROOTFS_URL="http://download.exorembedded.net:8080/Public/usom02/rootfs/core-image-exor-x11-us02-kit-v2.0.tar.gz"
   UBOOT_URL="http://download.exorembedded.net:8080/Public/usom02/bootloader/us02-kit-uboot-v2.0.tar.gz"
   ;;
"us03")
   KERNEL_URL="http://download.exorembedded.net:8080/Public/usom03/kernel/us03-kit-kernel-v2.0.tar.gz"
   ROOTFS_URL="http://download.exorembedded.net:8080/Public/usom03/rootfs/core-image-exor-x11-us03-kit-v2.0.tar.gz"
   UBOOT_URL="http://download.exorembedded.net:8080/Public/usom03/bootloader/us03-kit-uboot-v2.0.tar.gz"
   ;;
*)
   echo "Uknown machine: $machine"
   usage $0
   exit 1
   ;;
esac

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

FILES_DIR="$BASE_DIR/mkSDTool_files"
DOWNLOAD_DIR="$FILES_DIR/$machine"
mkdir -p "$DOWNLOAD_DIR"

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

echo "Using kernel $kernel"

if [ -n "$uboot" -a ! -f "$uboot" ]; then
   echo "ERROR: specified uboot tarball not found"
   exit 1
else
   uboot="$DOWNLOAD_DIR/uboot.tar.gz"
   if [ ! -f "$uboot" ]; then
      echo Downloading uboot from: $UBOOT_URL...
      wget $UBOOT_URL -O $DOWNLOAD_DIR/uboot.tar.gz
   fi
fi

echo "Using uboot $uboot"

if [ -n "$rootfs" -a ! -f "$rootfs" ]; then
   echo "ERROR: specified rootfs tarball not found"
   exit 1
else
   rootfs="$DOWNLOAD_DIR/rootfs.tar.gz"
   if [ ! -f "$rootfs" ]; then
      echo Downloading rootfs from: $ROOTFS_URL...
      wget $ROOTFS_URL -O $DOWNLOAD_DIR/rootfs.tar.gz
   fi
fi

echo "Using rootfs $rootfs"

if ( echo $machine | grep -q "us01-" ); then

   if [ -n "$xloader" -a ! -f "$xloader" ]; then
      echo "ERROR: specified xloader tarball not found"
      exit 1
   else
      xloader="$DOWNLOAD_DIR/xloader.tar.gz"
      if [ ! -f "$xloader" ]; then
         echo Downloading xloader from: $XLOADER_URL...
         wget $XLOADER_URL -O $DOWNLOAD_DIR/xloader.tar.gz
      fi
   fi

   echo "Using xloader $xloader"

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 || true
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

# Some systems may try to re-mount partitions
sleep 10
umount -l $device* || true

# Format partitions
echo "Formating BOOT partition..."
mkfs.vfat -F 32 -n "BOOT" ${device}1
sync
echo "Formating ROOT partition ..."
mkfs.ext4 -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..."
tar xzf $rootfs -C /media/mk_ROOT

if ( echo $machine | grep -q "us01-" ); then

   mkdir -p /media/mk_BOOT/boot
   tar xzf $kernel --no-same-owner -C /media/mk_BOOT/boot
   tar xzf $uboot --no-same-owner -C /media/mk_BOOT
   tar xzf $xloader --no-same-owner -C /media/mk_BOOT

elif [ "$machine" == "us02" ]; then

   tar xzf $kernel --no-same-owner -C /media/mk_BOOT/
   tar xzf $uboot -C $FILES_DIR
   dd if=$FILES_DIR/u-boot.img of=${device}3 bs=64k seek=4
   rm $FILES_DIR/u-boot.img

elif [ "$machine" == "us03" ]; then

   mkdir -p /media/mk_BOOT/boot
   tar xzf $kernel --no-same-owner -C /media/mk_BOOT/boot
   tar xzf $uboot -C $FILES_DIR
   dd if=$FILES_DIR/u-boot.imx of=${device} bs=1k seek=1
   rm $FILES_DIR/u-boot.imx

fi

echo
echo Syncing...
sync

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

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

echo
echo "Completed!"

