#!/bin/sh
# geninitrd mod: suspend
USE_SUSPEND=${USE_SUSPEND:-yes}

# resume device
resume_dev=""

# setup geninitrd module
# @access	public
setup_mod_suspend() {
	# XXX this needs tuxonice loaded first
	if is_yes "$USE_SUSPEND" && is_yes "$USE_TUXONICE"; then
		warn "Tuxonice and mainline suspend are exclusive!"
	fi

	resume=$(find_tool $(get_libdir /usr/LIBDIR/suspend/resume) $initrd_dir/resume /usr/sbin/resume)

	if [ ! -x "$resume" ] || [ ! -f /etc/suspend.conf ]; then
		USE_SUSPEND=no
	else
		resume_dev="$(awk '/^resume device =/ { print $4 } ' /etc/suspend.conf)"
		if [ -z "$resume_dev" ]; then
			warn "Option 'resume device' not found in /etc/suspend.conf. Disabling suspend support."
			USE_SUSPEND=no
		fi
	fi
}

# find modules for for suspend
# @access	public
find_modules_suspend() {
	resume_dev="$(awk '/^resume device =/ { print $4 } ' /etc/suspend.conf)"

	# save state
	local vgvolumes=$LVM_VGVOLUMES
	find_modules_for_devpath $resume_dev

	# check for saved state, differenciate between rootfs VG
	if [ "$LVM_VGVOLUMES" != "$vgvolumes" ]; then
		# save suspend VG int oseparate var
		LVM_SUSPENDVG=$LVM_VGVOLUMES
		LVM_VGVOLUMES=$vgvolumes
		verbose "suspend device is on LVM"
	fi
}

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

	verbose "Setting up suspend..."

	mknod -m 640 $DESTDIR/dev/snapshot c 10 231
	mkdir -p $DESTDIR${resume_dev%/*}
	inst $resume_dev $resume_dev

	inst /etc/suspend.conf /etc/suspend.conf
	inst_exec $resume /bin/resume

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