#!/usr/bin/bash

# Propagate any xtrace (set -x) setting to sub-scripts
export SHELLOPTS

set -e

usage()
{
cat 1>&2 << EOF
Usage: $0 Options

Options:
   -h      Show this message
   -d      block device                           (required)
   -m      mount point                            (required)
   -g      LVM volume group name                  (optional, default: vg0)
   -l      LVM logical volume name                (optional, default: ebs)

CAUTION: block device (-d) will be erased completely and
         the filesystem will be re-built hence the data stored
         on the block device won't be recoverable. Make sure
         to create a backup from the data stored on the block
         device first.

EOF
}

while getopts ":hd:m:g:l:c" opt; do
	case $opt in
		m)
			MOUNTPOINT=$OPTARG
			;;
		d)
			DEV=$OPTARG
			;;
		g)
			VOLGROUP=$OPTARG
			;;
		l)
			LOGICALVOL=$OPTARG
			;;
		h)
			usage
			exit 0
			;;
		:)
			usage
			echo "Option -$OPTARG requires an argument." >&2
			exit 1
			;;
		\?)
			usage
			echo "Invalid option: -$OPTARG" >&2
			exit 1
			;;
	esac
done

if [ $OPTIND -eq 1 ]; then
	usage
	exit 1
fi

VOLGROUP=${VOLGROUP:-vg0}
LOGICALVOL=${LOGICALVOL:-ebs}

if [ -z $DEV ]; then
	usage && echo "Error: -d is mandatory" >&2 && exit 1
fi

if [ -z $MOUNTPOINT ]; then
	usage && echo "Error: -m is mandatory" >&2 && exit 1
fi

function init_ebs_volume()
{
	systemctl enable glusterd
	systemctl --quiet --no-block start glusterd

	if ! pvdisplay $DEV >/dev/null 2>&1 && ! mountpoint $MOUNTPOINT >/dev/null 2>&1; then
		dd if=/dev/zero of=$DEV bs=512 count=1024
		pvcreate --force $DEV
		vgcreate --force $VOLGROUP $DEV
		lvcreate -l +100%FREE $VOLGROUP -n $LOGICALVOL
		mkfs.xfs -i size=512 /dev/$VOLGROUP/$LOGICALVOL

		mkdir -p $MOUNTPOINT
		echo "$(xfs_admin -u /dev/$VOLGROUP/$LOGICALVOL | sed -e 's/ //g') $MOUNTPOINT xfs defaults 0 0" >> /etc/fstab
		mount $MOUNTPOINT
	fi

	if ! mountpoint $MOUNTPOINT >/dev/null 2>&1; then
		mount $MOUNTPOINT
	fi
}

init_ebs_volume
