#!/bin/sh

set -e
set -x

# Previous versions of this script used the device as parameter.
# We now use /etc/oci/data-disks, which contains a list of devices.

# This is the "9" in cloud1-volume-9 ...
COMP_NN=$(hostname | cut -d. -f1 | cut -d- -f3)
# This is the "cloud1" in cloud1-volume-9 ...
CLUST=$(hostname | cut -d. -f1 | cut -d- -f1)

if ! [ -e /etc/oci/cinder-separate-volume-groups ] ; then
	VG_NAME=${CLUST}vol${COMP_NN}vg0
else
	VG_START_NAME=${CLUST}vol${COMP_NN}vg
fi

# Make the PVs with all blcok devices,
for i in $(cat /etc/oci/data-disks); do
	# Make the PV if it's possible
	if pvcreate -t /dev/${i} ; then
		pvcreate /dev/${i}
	fi
done

if ! [ -e /etc/oci/cinder-separate-volume-groups ] ; then
	LIST_PV_DEVS=$(cat /etc/oci/data-disks | tr '\n' ' ')
	LIST_PV_PATH=""
	for i in ${LIST_PV_DEVS} ; do
		LIST_PV_PATH="${LIST_PV_PATH} /dev/${i}"
	done

	# Make the VG with all drives as param
	VG=$(vgdisplay -c | head -n 1 | cut -d: -f1 | awk '{print $1}')
	if ! [ "${VG}" = "${VG_NAME}" ] ; then
		vgcreate ${VG_NAME} ${LIST_PV_PATH}
		vgchange -a y ${VG_NAME}
	fi
else
	COUNT=0
	LIST_PV_DEVS=$(cat /etc/oci/data-disks | tr '\n' ' ')
	for i in $(cat /etc/oci/data-disks); do
		VG_NAME=${VG_START_NAME}${COUNT}
		VG=$(vgdisplay -c | grep -q ${VG_NAME} | head -n 1 | cut -d: -f1 | awk '{print $1}')
		if ! [ "${VG}" = "${VG_NAME}" ] ; then
			vgcreate ${VG_NAME} /dev/${i}
			vgchange -a y ${VG_NAME}
		fi
		COUNT=$(( ${COUNT} + 1 ))
	done
fi
