#!/bin/sh
############################################################################## 
# Copyright (C) 2008 - 2012 vortexbox.org
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# Name: format-usb-drive
# Usage: format-usb-drive <device name>; e.g. format-usb-drive /dev/sdb
#
# Script to format a USB drive for use as a VortexBox backup drive.
# Use parted to partition the drive instead of sfdisk.
# Create a GUID Partition Table (GPT) on the drive instead of an MBR partition table.
# This will ensure correct partitioning of drives larger that 2TB.
# Then create an NTFS filesystem on the drive.
# Finally, create a VortexBox.txt file on the drive to mark it as a VortexBox backup drive.
#
# Author: Ron Olsen <ronolsen@comcast.net>
# Date: Mon Feb 6 2012
# Version: 1.0
##############################################################################

if [ $# -ne 1 ]
then
    echo "Usage: format-usb-drive <device-name>"
    exit 1
fi

USB_DRIVE=$1 PARTITION=${USB_DRIVE}1

# Make sure device is a USB drive

if ! udevadm info --query=path --name $USB_DRIVE | grep usb > /dev/null 2>&1
then
    echo "$USB_DRIVE is not a USB device"
    exit 3
fi

# Make sure drive is not mounted

if mount | grep $PARTITION > /dev/null 2>&1
then
    echo "$PARTITION is mounted; unmounting..."
    umount $PARTITION
fi

# Partition the drive using parted
echo "Invoking parted..."
parted -a optimal $USB_DRIVE --script -- mklabel gpt mkpart primary ntfs 0 -0 name 1 "VortexBox_Backup" > /dev/null 

if [ $? -ne 0 ]
then
    echo "parted failed!"
    exit 4
fi

# Format the drive with an NTFS filesystem

echo "Invoking mkntfs..."
mkntfs -f --label "VortexBox Backup" $PARTITION > /dev/null

if [ $? -ne 0 ]
then
    echo "mkntfs failed!"
    exit 5
fi

# Mount the drive

mount $PARTITION /backup

if [ $? -ne 0 ]
then
    echo "mount failed!"
    exit 6
fi

# Create a VortexBox.txt file on the drive

echo "This is a VortexBox backup drive created on $(date)" > /backup/VortexBox.txt

# Unmount the drive when done

umount /backup

# Done

parted $USB_DRIVE print
