#!/bin/sh
# vim: noexpandtab
#
# Copyright (C) 2022, Rockchip Electronics Co., Ltd
#
# Based on pm-utils-1.4.1's pm-action.
#
# 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
#

[ -d "/usr/lib/pm-utils/" ] || exit 0

# The rule here? Simplicity.
export STASHNAME=pm-suspend
export STAGE="${1:-pre}"
export METHOD="${2:-suspend}"
. "/usr/lib/pm-utils/pm-functions"

case "$METHOD" in
	suspend*)	ACTION=suspend;   REVERSE=resume ;;
	hibernate) 	ACTION=hibernate; REVERSE=thaw ;;
	*)		exit 1 ;;
esac

remove_suspend_lock()
{
	release_lock "${STASHNAME}.lock"
}

try_lock "${STASHNAME}.lock" || exit 1

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

# clean up from the last run
rm -rf "${STORAGEDIR}"
mkdir -p "${STORAGEDIR}"
# save our parameter list.
[ -f "$PARAMETERS" ] || echo '' >"$PARAMETERS"
add_parameters $PM_CMDLINE
update_parameters

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

case "$STAGE" in
	pre)
		log "$(date): Running hooks for $ACTION."
		run_hooks sleep "$ACTION $METHOD"
		log "$(date): performing $METHOD"
		;;
	post)
		log "$(date): Running hooks for $REVERSE"
		run_hooks sleep "$REVERSE $METHOD" reverse
		log "$(date): Finished."
		;;
esac
