#!/bin/bash
#
# Copyright (c) Citrix Systems 2008. All rights reserved.
#

###
# Check a disk and prepare it for sr-create - basically, remove any
# physical volumes, etc.

force=
full_erase=

while getopts "fer" opt ; do
	case $opt in
		f) force=yes ;;
		e) full_erase=blank ;;
		r) full_erase=random ;;
	esac
done

shift $((${OPTIND} - 1))

disk="${1}"

# valid args?
if [ -z "${disk}" ] ; then
	echo "This tool prepares a disk to hold a storage repository by removing any data"
	echo "previously stored on it that may interfere with operation of the XenSource"
	echo "tools."
	echo
	echo "Usage: diskprep [-f] [-e|-r] volume"
	echo "  -f: forcefully prepare the volume - use with care."
	echo "  -e: Erase the volume completely with zeroes"
	echo "  -r: Erase the volume completely with random data"
	echo "  volume: is the path to a device node, e.g. /dev/sdb1" 
	echo
	exit 1
fi

# Were we passed a symlink?
if [ -L "${disk}" ]; then
    echo >&2 "${disk} is a symlink, de-referencing to $(readlink -f ${disk})"
    disk="$(readlink -f ${disk})"
fi

# is it a device node?
if [ ! -b "${disk}"  ]; then
	echo "${disk} is not a block device - aborting."
	exit 2
fi

echo "Initialising disk $disk..."

# is there a PV here?
if pvs | grep -q ${disk} ; then
	vg=$(pvs | grep ${disk} | awk '{print $2;}')
	if [ -z "${force}" ] ; then
		echo "The disk has an LVM physical volume label.  This tool will not remove this"
		echo "label without the -f (force) flag present.  This operation is dangerous and"
		echo "may lead to data loss in the volume group ${vg}."
		exit 2
	else
		echo "* LVM physical volume label found - de-activating VG and removing"
		if ! vgchange -a n ${vg} ; then
			echo "  Error deactivating volume group ${vg}, attempting to continue."
		fi
		pvremove -ff -y ${disk}

		# now see if any other PVs were part of this volume group:
		if pvs | grep -q "${vg}" ; then
			echo "* Attempting to reduce broken volume group"
			vgreduce --removemissing "${vg}"
		fi
	fi
fi

# erase the start of the volume to get rid of other metadata:
if [ -z "${full_erase}" ] ; then
	echo "* Erasing start of volume"
	dd if=/dev/zero of=${disk} count=10 bs=1024k &>/dev/null
elif [ "${full_erase}" == "blank" ] ; then
	echo "* Erasing volume"
	dd if=/dev/zero of=${disk} &>/dev/null
elif [ "${full_erase}" == "random" ] ; then
	echo "* Erasing volume with pseudo-random data"
	dd if=/dev/urandom of=${disk} &>/dev/null
fi

echo "Complete."
