#!/bin/sh

# Special-case suspend-then-hibernate:
#
# If the system was woken by a battery alarm, then systemd will call this script
# to resume from suspend and then enter hibernation. Don't call into the full
# nvidia-sleep.sh script in that case, just write directly to
# /proc/driver/nvidia/suspend.
if [ "$2" = "suspend-then-hibernate" -a -f /proc/driver/nvidia/suspend ]; then
    case "$1:$SYSTEMD_SLEEP_ACTION" in
        post:*)
            # Normally, we would want to call the full nvidia-sleep.sh here, but
            # that is a problem for suspend-after-failed-hibernate: systemd
            # calls this script with the sleep action set to "hibernate" but
            # doesn't tell us whether the hibernate succeeded or failed. If it
            # failed, it is important not to perform the VT switch back to the
            # Xorg server before systemd attempts to suspend again. Instead,
            # rely on the nvidia-resume.service systemd unit to do that.
            echo resume > /proc/driver/nvidia/suspend
            ;;
        pre:hibernate)
            echo hibernate > /proc/driver/nvidia/suspend
            ;;
        pre:suspend-after-failed-hibernate)
            echo suspend > /proc/driver/nvidia/suspend
            ;;
    esac
    exit 0
fi

case "$1" in
    post)
        /usr/bin/nvidia-sleep.sh "resume"
        ;;
esac
