#!/bin/sh
# LVM snapshot rebooter : wait for any merging LV and reboot once done
# Use this it to workaround GRUB limitation : it does not handle LV with merging snapshot

PREREQ="lvm"
prereqs()
{
   echo "$PREREQ"
}

case $1 in
prereqs)
   prereqs
   exit 0
   ;;
esac

. /scripts/functions

if [ ! -x "/sbin/lvm" ]; then
   panic "lvs executable not found"
fi

get_lv_snapshot_merging() {
	# This will print a list of "vg/lv" marked for merging
	/sbin/lvm lvs --select 'lv_merging!=0' --noheadings --separator '/' -o vg_name,lv_name
}

log_begin_msg "Starting LVM Snapshot rebooter"

# Wait for LVM elements to appear and be activated by udev
wait_for_udev 10

lv_merging=$(get_lv_snapshot_merging)
if [ -n "$lv_merging" ] ; then
	log_end_msg
	for lv in $lv_merging; do
		log_begin_msg "  Merging $lv"
		/sbin/lvm lvchange --sysinit -ay "$lv" # lvmpolld/dmeventd no yet available
		/sbin/lvm lvpoll --polloperation merge --interval 1 --config activation/monitoring=0 "$lv"
		log_end_msg
	done
	log_success_msg "Snapshot merging complete, will reboot..."
	touch /run/initramfs/do_reboot
else
	log_success_msg "Done. (No LVM snapshot need merging)"
fi

exit 0
