#!/bin/bash
#
# pm-utils-hooks-compat.sh - run pm-utils sleep hooks from systemd
#
# Copyright (C) 2014 Guido Berhoerster <gber@opensuse.org>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#

shopt -s nullglob
export PATH=/sbin:/usr/sbin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin
export LC_ALL=C

PM_UTILS_SLEEP_D_PATH=/usr/lib/pm-utils/sleep.d
PM_UTILS_ETC_SLEEP_D_PATH=/etc/pm/sleep.d
export PM_FUNCTIONS=/usr/lib/pm-utils/functions

function run_script {
    if [[ -r ${1} && -x ${1} && -O ${1} && \
            ! -e ${PM_UTILS_ETC_SLEEP_D_PATH}/${1##*/} ]]; then
        "$@"
    fi
}

[[ -r $PM_FUNCTIONS ]] || exit 1

scripts=( ${PM_UTILS_SLEEP_D_PATH}/*[!~] )
if [[ $1 == "pre" ]]; then
    for (( i = 0; i < ${#scripts[@]}; i++ )); do
        case "$2" in
            suspend)
                run_script "${scripts[i]}" suspend suspend
                ;;
            hibernate)
                run_script "${scripts[i]}" hibernate hibernate
                ;;
            hybrid-sleep)
                run_script "${scripts[i]}" suspend suspend-hybrid
                ;;
        esac
    done
else
    for (( i = ${#scripts[@]}; i >= 0; i-- )); do
        case "$2" in
            suspend)
                run_script "${scripts[i]}" resume suspend
                ;;
            hibernate)
                run_script "${scripts[i]}" thaw hibernate
                ;;
            hybrid-sleep)
                run_script "${scripts[i]}" resume suspend-hybrid
                ;;
        esac
    done
fi
