# This script creates a backup of a bootable Pi image on an SD card (or,
# actually, a backup of whatever contents happen to be on the specified
# device).

# The script should be called with 1 or 2 parameters: the name of the device
# that has been assigned to the SD card (e.g., disk6) and, optionally,
# the word "zip".  If "zip" is specified as the second parameter, the
# script will create a compressed version of the backup.

# The name of the backup will be pi485 with a timestamp appended and a
# .img suffix (for example, pi485_09Jan16-18:11:18.img), or the same 
# but with an additional .gz suffix if the backup is compressed
# (for example, pi485_09Jan16-18:11:18.img.gz).

TODAYSDATE=`date +"%Y-%b-%d-%T"`
DISK_UTIL_CMD='diskutil list | grep " disk[0-9]$"'

if [ $# -eq 0 ]
    echo "USAGE:  $0 diskName [ zip ]"
    echo "         (e.g., $0 disk5"
    echo "             or $0 disk5 zip)"
    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)"


# 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).

diskutil unmountDisk /dev/$1
echo "After typing in password, be prepared to wait."
if [ $# -eq 1 ]
    sudo dd bs=1m if=/dev/r$1 of=$BACKUP_FILENAME
    sudo dd bs=1m if=/dev/r$1 | gzip -c > $BACKUP_FILENAME
diskutil unmountDisk /dev/$1
echo "Done making backup ($BACKUP_FILENAME)."