#!/bin/bash

sbindir="/usr/sbin"

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

clustered_vgs() {
	"$lvm_vgs" --noheadings -o vg_name -S 'vg_clustered=1' 2>/dev/null
}

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" ] || [ "$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"
