#!/bin/sh
# geninitrd mod: swsusp
#
USE_SWSUSP=${USE_SWSUSP:-yes}

# resume device
swap_dev=""

# setup geninitrd module
# @access	public
setup_mod_swsusp() {
    	if ! is_yes "$USE_SWSUSP"; then
		return
	fi

	swap_dev="$(awk '/^\/dev\// { print $1 }' /proc/swaps | grep -v /dev/zram | head -1)"
	if [ -z "$swap_dev" ]; then
	    warn "Cannot determine swap device. You may try add specific device to kernel command line. Disabling swsusp support."
	    USE_SWSUSP=no
	else
	    verbose "swsusp: will try to resume from swap device $swap_dev"
	fi
}

# find modules for for swsusp
# @access	public
find_modules_swsusp() {
    	swap_dev="$(awk '/^\/dev\// { print $1 }' /proc/swaps | grep -v /dev/zram | head -1)"

	# save state
	local vgvolumes=$LVM_VGVOLUMES
	find_modules_for_devpath $swap_dev

	# check for saved state, differenciate between rootfs VG
	if [ "$LVM_VGVOLUMES" != "$vgvolumes" ]; then
		# add swap device to LVM_SUSPENDVG
		LVM_SUSPENDVG="$LVM_SUSPENDVG $LVM_VGVOLUMES"
		LVM_VGVOLUMES=$vgvolumes
		verbose "swap device is on LVM"
	fi
}

# generate initrd fragment
# @access	public
initrd_gen_swsusp() {
	if ! is_yes "$USE_SWSUSP"; then
		return
	fi

	verbose "Setting up swsusp..."

	mkdir -p $DESTDIR${swap_dev%/*}
	inst $swap_dev $swap_dev

        mount_dev
	mount_sys
        echo "swap_dev=$swap_dev" | add_linuxrc

	add_linuxrc <<-'EOF'
	resume=no
	for arg in $CMDLINE; do
		if [ "${arg##resume=/dev/}" != "${arg}" ]; then
			swap_dev=${arg##resume=}
			resume=yes
		elif [ "${arg##resume=}" != "${arg}" ]; then
			resume=${arg##resume=}
		fi
	done

	if [ "$resume" = "yes" ] && [ -n "$swap_dev" ]; then
	        echo "Resuming from $swap_dev..."
		echo "$swap_dev" > /sys/power/resume
	fi
	EOF
}
