#!/bin/bash

# cleanup
# trap ctrl-c and call ctrl_c()
trap cleanup INT

function cleanup() {
  rm -f /tmp/noobs.zip
  umount -f /tmp/sdcard.$$ >/dev/null 2>&1
  rmdir /tmp/sdcard.$$
  echo "Aborted."
  exit 1
}

if [[ $EUID -ne 0 ]]; then
  echo "ERROR: this script must be run as root (i.e. using \`sudo'.)"
  exit 1
fi

PATH=${PATH}:/sbin:/usr/sbin

if [ -z "$1" ]; then
  echo "USAGE: pi_sd_prep.sh device"
  exit 1
fi

if [ ! -b "$1" ]; then
  echo "ERROR: no such device: $1"
  exit 1
fi

DEV="$1"

echo "Unmoounting all partitions on $DEV:"
PARTS="`df | grep ^$DEV | awk '{ print $1 }'`"
if [ ! -z "$PARTS" ]; then
  for PART in $PARTS; do
    echo "...$PART"
    umount "$PART"
  done
fi
echo "...done"

echo "Preparing partition table on $DEV:"
dd if=/dev/zero of=/dev/sdb bs=512 count=10 >/dev/null 2>&1
echo -e "n\np\n1\n\n\nt\nb\na\n1\nw\nq\n" | fdisk $DEV >/dev/null 2>&1
echo "...done"

echo "Formatting partition on $DEV:"
mkfs.vfat -n "NOOBS" ${DEV}1
# -F 16
echo "...done"

echo "Mounting partition on $DEV:"
mkdir -p /tmp/sdcard.$$
mount -t vfat "${DEV}1" /tmp/sdcard.$$
echo "...done"

echo "Downloading latest NOOBS:"
curl -#Lo /tmp/noobs.zip http://downloads.raspberrypi.org/NOOBS_latest
echo "...done"

echo "Unzipping to SD card..."
unzip -q -d /tmp/sdcard.$$ /tmp/noobs.zip
echo "...done"

# get NOOBS version info
NOOBS_VERSION=`grep -i "^NOOBS Version:" /tmp/sdcard.$$/BUILD-DATA | cut -d':' -f2  | tr -d '[[:space:]]'`
BUILD_DATE=`grep -i "^Build-date:" /tmp/sdcard.$$/BUILD-DATA | cut -d':' -f2  | tr -d '[[:space:]]'`

echo "unmounting SD card..."
sync;sync;sync
umount /tmp/sdcard.$$
echo "...done"

rm -f /tmp/noobs.zip
rmdir /tmp/sdcard.$$
echo "NOOBS $NOOBS_VERSION ($BUILD_DATE) has been installed and is ready to be booted."
