#!/bin/sh
#
# Simple suspend script
#
# Copyright 2006 Red Hat, Inc.
#
# Based on work from:
#    Bill Nottingham <notting@redhat.com>
#    Peter Jones <pjones@redhat.com>
#    David Zeuthen <davidz@redhat.com>
#    Richard Hughes <richard@hughsie.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

# The rule here? Simplicity.

. "/usr/lib/pm-utils/pm-functions"

help()
{
	echo "${0##*/} [options]"
	echo
	echo "Options can change how suspend or hibernate is done."
	run_hooks sleep help
	command_exists sleep_method_help && sleep_method_help
	exit 0
}

if [ "$(id -u)" != "0" ]; then
	echo This utility may only be run by the root user. 1>&2
	exit 1
fi
take_suspend_lock || exit 1

# make sure we release the lock no matter how we exit
trap remove_suspend_lock 0

while [ $# -gt 0 ]
do
	[ "$1" = "--help" ] && help
	shift
done

METHOD="$(echo ${0##*pm-} |tr - _)"

"check_$METHOD" || { echo "System does not support $METHOD sleep."; exit 1; }

case "$METHOD" in
	suspend*) 	ACTION=suspend;   REVERSE=resume ;;
	hibernate) 	ACTION=hibernate; REVERSE=thaw ;;
	*)		echo "Don't know how to ${METHOD}."
			exit 1 ;;
esac

init_logfile "${PM_LOGFILE}"
log "Initial commandline parameters: $PM_CMDLINE"
load_hook_blacklist
load_hook_parameters

# Make sure we are not inhibited before we start.
rm -f "${INHIBIT}"

if command_exists "do_$METHOD" ; then
    # run the sleep hooks
    log "$(date): Running hooks for $ACTION."
    run_hooks sleep "$ACTION"
    # Sleep only if we know how and if a hook did not inhibit us.
    if [ ! -e "$INHIBIT" ]; then
        log "$(date): performing ${METHOD}"
        sync
        "do_$METHOD"
        log "$(date): Awake."
    else
        log "$(date): Inhibit found, will not perform ${METHOD}"
    fi
    log "$(date): Running hooks for $REVERSE"
    # run the sleep hooks in reverse with the wakeup action
    run_hooks sleep "$REVERSE" reverse
    log "$(date): Finished."
else
    log "$(date): Missing module to perform $METHOD - abort."
    exit 1
fi
