#!/bin/bash
#
# Copyright (C) 2014 - 2018 x-odos GnbH
#

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

USB_DRIVE=$1 
PARTITION=${USB_DRIVE}1
STICK=$2

# 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"
    echo '{"format":"error", "time":"'$NOW'", "status":"not a USB device"}' > /var/log/format_usb.json
    exit 3
fi

# Make sure drive is not mounted

if mount | grep $PARTITION > /dev/null 2>&1
then
    echo "$PARTITION is mounted; unmounting..."
    echo '{"format":"error", "time":"'$NOW'", "status":"mounted"}' > /var/log/format_usb.json
    umount --force $PARTITION
fi

if /bin/mount | /bin/grep $PARTITION  > /dev/null
then
	echo "$PARTITION is mounted; unmounting..."
   	echo '{"format":"error", "time":"'$NOW'", "status":"mounted"}' > /var/log/format_usb.json
	while /bin/mount | /bin/grep $PARTITION > /dev/null
	do 
		sudo  umount --force $PARTITION
		sleep 2
	done
fi

# Partition the drive using parted
echo "Cleaning drive..."
echo '{"format":"cleaning", "time":"'$NOW'", "status":"Cleaning Drive"}' > /var/log/format_usb.json
sgdisk --zap-all --clear --mbrtogpt $USB_DRIVE > /dev/null 
if [[ $STICK != 1 ]]; then
	sgdisk -N 1 -c 1:"x-odos_Backup" -t 1:0700 $USB_DRIVE > /dev/null 
else
	sgdisk -N 1 -c 1:"x-odos" -t 1:0700 $USB_DRIVE > /dev/null 
fi
if [ $? -ne 0 ]
then
    echo "sgdisk failed!"
    echo '{"format":"cleaning", "time":"'$NOW'", "status":"Cleaning failed!"}' > /var/log/format_usb.json

    exit 4
fi

# Format the drive with an NTFS filesystem

echo "Formatting backup drive with NTFS..."
echo '{"format":"cleaning", "time":"'$NOW'", "status":"Formatting"}' > /var/log/format_usb.json
if [[ $STICK != 1 ]]; then
	mkntfs -f --label "x-odos Backup" $PARTITION > /dev/null
else
	mkntfs -f --label "x-odos" $PARTITION > /dev/null
fi 

if [ $? -ne 0 ]
then
    echo "mkntfs failed!"
    echo '{"format":"cleaning", "time":"'$NOW'", "status":"Formatting failed!"}' > /var/log/format_usb.json
    exit 5
fi

sleep 2
ntfsfix $PARTITION > /dev/null

# Mount the drive
if [[ $STICK != 1 ]]; then 
	# Mount the drive
	mount $PARTITION /backup

	if [ $? -ne 0 ]; then
  		echo "mount failed!"
  		echo '{"format":"mounting", "time":"'$NOW'", "status":"Drive mount failed!"}' > /var/log/format_usb.json
   		exit 6
	fi
	# Create a x-odos.txt file on the drive
	echo "This is a xo|one backup drive created on $(date)" > /backup/xo-one.txt
	cd /fusb
	cp -r /fusb/* /backup
	# Unmount the drive when done
	umount /backup
	echo '{"format":"finished", "time":"'$NOW'", "status":"Preparing Backup-Drive finished"}' > /var/log/format_usb.json
fi 
# Done

parted $USB_DRIVE print
