#!/bin/sh
#
# $NetBSD: lvm,v 1.8 2021/08/21 23:00:30 andvar Exp $
#

# PROVIDE: lvm
# REQUIRE: root devpubd
# BEFORE:  DISKS

$_rc_subr_loaded . /etc/rc.subr

name="lvm"
rcvar=$name
start_cmd="lvm_start"
stop_cmd="lvm_stop"

ifs_restore="$IFS";

lvm_start()
{
       if [ -x /sbin/dmsetup ]; then
               /sbin/dmsetup version >/dev/null
               if [ $? -ne 0 ]; then
                       warn "Device-mapper not present in kernel"
                       return 1;
               fi
       fi

       if [ -x /sbin/lvm ]; then
               echo "Configuring lvm devices."

               # Scan for all available VG's
               /sbin/lvm vgscan --mknodes --ignorelockingfailure >/dev/null

               # Activate all LV's and create appropriate nodes in /dev
               /sbin/lvm vgchange --ignorelockingfailure -a y >/dev/null
               LV_LIST=$(/sbin/lvm vgdisplay -C -o vg_name --noheadings 2>/dev/null)
               echo " Activated Volume Groups:" $LV_LIST
       fi
}

lvm_stop()
{
       if [ -x /sbin/dmsetup ]; then
               /sbin/dmsetup version >/dev/null
               if [ $? -ne 0 ]; then
                       warn "Device-mapper not present in kernel"
                       return 1;
               fi
       fi

       if [ -x /sbin/lvm ]; then
               echo "Unconfiguring lvm devices."

               LOGICAL_VOLUMES=$(/sbin/lvm lvdisplay -C -o vg_name,lv_name \
                       -O vg_name --separator \/ --noheadings 2>/dev/null)
               VOLUME_GROUPS=$(/sbin/lvm vgdisplay -C -o vg_name \
                       --separator " " --noheadings 2>/dev/null)

               for lv in ${LOGICAL_VOLUMES}; do
                       LV_IS_ACTIVE=$(/sbin/lvm lvdisplay -C --noheadings \
                               -o lv_attr $lv)
                       case $LV_IS_ACTIVE in
                       *a*)
                               echo "  Shutting Down logical volume: ${lv}"
                               /sbin/lvm lvchange -an --ignorelockingfailure \
                                       -P ${lv} >/dev/null
                               ;;
                       esac
               done

               for vg in ${VOLUME_GROUPS}; do
                       # Set IFS to field separator
                       IFS=":"
                       set -- $(/sbin/lvm vgdisplay -cA ${vg} 2>/dev/null)
                       # The seventh parameter is number of opened LVs in a Volume Group
                       VG_HAS_ACTIVE_LV=$7
                       IFS="$ifs_restore";

                       if [ "${VG_HAS_ACTIVE_LV}" = 0 ]; then
                               echo "  Shutting Down volume group: ${vg}"
                               /sbin/lvm vgchange -an --ignorelockingfailure \
                                       -P ${vg} >/dev/null
                       fi
               done
       fi
}

load_rc_config $name
run_rc_command "$1"