#!/bin/bash

sbindir=@sbindir@

lvm_vgchange=${sbindir}/vgchange
lvm_vgscan=${sbindir}/vgscan
lvm_vgs=${sbindir}/vgs
lvm_lvm=${sbindir}/lvm

parse_clustered_vgs() {
	while read -r name attrs;
	do
		test "${attrs:5:1}" == 'c' && echo -n "$name "
	done
}

# NOTE: replace this with vgs, once display filter per attr is implemented.
clustered_vgs() {
	${lvm_vgs} -o vg_name,vg_attr --noheadings | parse_clustered_vgs
}

activate() {
	eval local $(${lvm_lvm} dumpconfig devices/obtain_device_list_from_udev 2>/dev/null) 2>/dev/null
	if [ $? -ne 0 ]; then
		echo "Warning: expected single couple of key=value in output of dumpconfig"
	fi

	if [ -z $obtain_device_list_from_udev -o $obtain_device_list_from_udev -ne 1 ]; then
		echo -n "lvm.conf option obtain_device_list_from_udev!=1: Executing vgscan"
		${lvm_vgscan} > /dev/null 2>&1
	fi

	echo -n "Activating ${LVM_VGS:-"all VG(s)"}: "
	# Respect activation/auto_activation_volume_list!
	# Call "-aay" which is equal to "-aly" but respects this list.
        ${lvm_vgchange} -aay $LVM_VGS || return 1

	return 0
}

deactivate()
{
	# NOTE: following section will be replaced by blkdeactivate script
	# with option supporting request to deactivate all clustered volume
	# groups in the system
	[ -z $LVM_VGS ] && LVM_VGS="$(clustered_vgs)"
	if [ -n "$LVM_VGS" ]; then
		echo -n "Deactivating clustered VG(s): "
		${lvm_vgchange} -anl $LVM_VGS || return 1
	fi

	return 0
}

case "$1" in
  deactivate)
	deactivate
	rtrn=$?
	;;
  activate)
	activate
	rtrn=$?
	;;
  *)
	echo $"Usage: $0 {activate|deactivate}"
	rtrn=3
	;;
esac

exit $rtrn