#!/bin/sh

# This script restores a bootable Pi image from a backup onto an SD card (or,
# actually, copies whatever is in the input file to the named device,
# completely overwriting the named device's previous contents).

# The script should be called with 2 parameters:
#   -- the name of the backup file
#   -- the name of the device that has been assigned to the SD card
#      (e.g., disk6).
# IT IS VERY IMPORTANT THAT THE DEVICE NAME BE CORRECT SO THAT YOU DON'T
# OVERWRITE THE CONTENTS OF THE WRONG DISK OR DEVICE!

DISK_UTIL_CMD='diskutil list | grep " disk[0-9]$"'

# Check that script was called with 2 parameters, and that first is a
# file with size greater than zero.
if [ $# -ne 2 ]
then
    echo "USAGE:  $0 backupFilename diskName"
    echo "         (e.g., $0 pi485_09Jan2016.img disk5"
    echo "             or $0 pi485_09Jan2016.img.gz disk5)"
    echo ""
    echo "Running $DISK_UTIL_CMD to help you determine disk name."
    eval $DISK_UTIL_CMD
    echo ""
    echo "Type diskutil info /dev/diskName to confirm that you have the right disk."
    echo "         (e.g., diskutil info /dev/disk5)"
    echo "IT IS VERY IMPORTANT THAT THE DEVICE NAME BE CORRECT SO THAT"
    echo "YOU DON'T OVERWRITE THE CONTENTS OF THE WRONG DISK OR DEVICE!"
    exit
elif [ ! -s $1 ]
then
    echo "$1 is not a valid filename."
    echo ""
    echo "USAGE:  $0 backupFilename diskName"
    echo "         (e.g., $0 pi485_09Jan2016.img disk5"
    echo "             or $0 pi485_09Jan2016.img.gz disk5)"
    exit
fi

BACKUP_FILENAME=$1
BASENAME=`basename -s .gz $BACKUP_FILENAME`
DISK_NAME=$2

# Implementation note on code below:
#      if="input file"; of="output file"; bs="block size" 
# dd will take FOREVER if left to the default (seems to be 512 bytes).

date 
diskutil unmountDisk /dev/$DISK_NAME
echo "After typing in password, be prepared to wait."
if [ $BACKUP_FILENAME = $BASENAME ]
then
    echo "$BACKUP_FILENAME is not a compressed image."
    sudo dd bs=1m if=$BACKUP_FILENAME of=/dev/r$DISK_NAME
else
    echo "$BACKUP_FILENAME is a compressed image -- will use gzip to uncompress."
    sudo sh -c "gzip -dc $BACKUP_FILENAME | dd bs=1m of=/dev/r$DISK_NAME"
fi
diskutil unmountDisk /dev/$DISK_NAME
date
echo "Done restoring $DISK_NAME from backup ($BACKUP_FILENAME)."