#!/bin/bash
#
# tries to format the backup target for eb-*

. /usr/sbin/eb-check-eb

echo "INFO: Checking that /dev/${EBPART} or ${EBMOUNTDIR} are not mounted yet"
mount |egrep "/dev/${EBPART}|${EBMOUNTDIR}" && exit 11

echo ""
echo "FYI: lsblk says:"
echo ""
lsblk
echo ""

echo "You will be asked to enter a LUKS password twice for formatting, and then again for mounting."
echo ""
echo "OK to LUKS-format /dev/${EBPART}?"
echo ""
echo -n "Enter yeS to continue, anything else to abort: "
read YESNO

if [ "$YESNO" != "yeS" ] ; then
  echo "ERROR: LUKS-formatting not confirmed by user, aborting."
  exit 12
fi

echo "GOOD: LUKS-formatting confirmed by user, starting ..."

echo "INFO: Calling cryptsetup -v luksFormat -c aes-xts-plain64 -s 512 -h sha512 --verify-passphrase /dev/${EBPART}"
cryptsetup -v luksFormat -c aes-xts-plain64 -s 512 -h sha512 --verify-passphrase /dev/${EBPART} || exit 21

echo "INFO: Calling cryptsetup -v luksOpen /dev/${EBPART} eb_crypted"
cryptsetup -v luksOpen /dev/${EBPART} eb_crypted || exit 22

echo "INFO: Calling mkfs.ext4 /dev/mapper/eb_crypted"
mkfs.ext4 /dev/mapper/eb_crypted || exit 23

echo "INFO: Calling mount -v /dev/mapper/eb_crypted /media/eb"
mount -v /dev/mapper/eb_crypted ${EBMOUNTDIR} || exit 24

echo "INFO: Calling mkdir -v ${EBMOUNTDIR}/${EBDESTBASE}"
mkdir -v ${EBMOUNTDIR}/${EBDESTBASE} || exit 25

echo "GOOD: Successfully created ${EBDESTBASE} on ${EBPART}:"
ls -ld ${EBMOUNTDIR}/${EBDESTBASE}

echo "INFO: Calling df -h ${EBMOUNTDIR}/${EBDESTBASE}"
df -h ${EBMOUNTDIR}/

echo "DONE formating /dev/${EBPART} as EB (external backup) and mounting it."
exit 0

