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

AddConfigHandler SysfsPowerStateConfigEnabler
AddOptionHandler SysfsPowerStateOptionHandler

AddConfigHelp "UseSysfsPowerState <state>" "Enables the use of /sys/power/state for suspending the machine. This requires a kernel supporting this interface. <state> must be one of the options listed by \`cat /sys/power/state\`, (eg mem, disk, or standby)."

AddShortOption "n"
AddLongOption "no-suspend"
AddOptionHelp "-n, --no-suspend (requires SysfsPowerState to be set)" "Disables actually suspending the system via /sys/power/state. This is useful for testing the suspend script itself."

SYSFS_POWER_STATE_FILE=/sys/power/state

SysfsPowerStateConfigEnabler() {
    [ "$1" != "usesysfspowerstate" ] && return 1
    [ -n "$USING_SYSFS_POWER_STATE" ] && return 0
    AddSuspendHook 10 EnsureSysfsPowerStateCapable
    AddSuspendHook 99 DoSysfsPowerStateSuspend
    USING_SYSFS_POWER_STATE=$2
    return 0
}

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

DoSysfsPowerStateSuspend() {
    if [ -z "$SYSFS_POWER_STATE_NO_SUSPEND" ] ; then
	vecho 1 "$EXE: Activating sysfs power state $USING_SYSFS_POWER_STATE ..."
	echo -n $USING_SYSFS_POWER_STATE > $SYSFS_POWER_STATE_FILE
    else
	vecho 1 "$EXE: Not actually suspending (--no-suspend given)"
    fi
    return 0
}

# EnsureSysfsPowerStateCapable: makes sure we have /sys/power/state and that
# the selection option is one of the available suspend modes.
EnsureSysfsPowerStateCapable() {
    if ! test -f $SYSFS_POWER_STATE_FILE ; then
	vecho 0 "Your kernel does not have power management built in."
	return 2
    fi
    if ! grep -q $USING_SYSFS_POWER_STATE $SYSFS_POWER_STATE_FILE ; then
	vecho 0 "Your kernel or machine does support the power state \"$USING_SYSFS_POWER_STATE\"."
	return 2
    fi

    return 0
}

# $Id: sysfs_power_state 423 2004-08-20 04:05:49Z dagobah $
