# -*- sh -*-
# vim:ft=sh:ts=8:sw=4:noet

AddConfigHandler USuspendConfigEnabler
AddOptionHandler USuspendOptionHandler

AddConfigHelp "UseUSuspend <boolean>" "If enabled, uses the 's2disk' program to suspend the machine with uswsusp."

AddShortOption "n"
AddLongOption "no-suspend"

USUSPEND_PROG=s2disk
USUSPEND_STATE_FILE=/sys/power/state
USUSPEND_DEVICE=/dev/snapshot

USuspendConfigEnabler() {
    [ "$1" != "useususpend" ] && return 1
    BoolIsOn "$1" "$2" || return 0
    [ -n "$USING_USUSPEND_STATE" ] && return 0
    if [ -n "$NO_COMPLAIN_UNSUPPORTED" ] ; then
	# Just bail silently if we don't detect it.
	if ! test -f $USUSPEND_STATE_FILE || ! test -c $USUSPEND_DEVICE ||
	   ! command -v $USUSPEND_PROG > /dev/null 2>&1 ; then
	    return 0
	fi
    fi
    UsingSuspendMethod ususpend
    AddSuspendHook 10 EnsureUSuspendCapable
    AddSuspendHook 99 DoUSuspend
    USING_USUSPEND_STATE=1
    return 0
}

USuspendOptionHandler() {
    [ -z "$USING_USUSPEND_STATE" ] && return 1
    case $1 in
	-n|--no-suspend)
	    USUSPEND_STATE_NO_SUSPEND=1
	    ;;
	*)
	    return 1
    esac
    return 0
}

DoUSuspend() {
    if [ -z "$USUSPEND_STATE_NO_SUSPEND" ] ; then
	vecho 1 "$EXE: Running $USUSPEND_PROG_PATH ..."
	$USUSPEND_PROG_PATH || vecho 0 "$EXE: $USUSPEND_PROG_PATH failed."
    else
	vecho 1 "$EXE: Not actually suspending (--no-suspend given)."
    fi
    return 0
}

EnsureUSuspendCapable() {
    if ! USUSPEND_PROG_PATH=$(command -v $USUSPEND_PROG) ; then
	vecho 0 "$USUSPEND_PROG not installed."
	return 2
    fi
    if ! test -f $USUSPEND_STATE_FILE ; then
	vecho 0 "Your kernel does not have power management built in."
	return 2
    fi
    if ! test -c $USUSPEND_DEVICE ; then
	vecho 0 "$USUSPEND_DEVICE device not found."
	return 2
    fi

    return 0
}

# $Id: ususpend 1053 2006-07-12 10:15:54Z bernard $
