#!/usr/bin/python

# This is an example pm-suspend hook that uses omhacks to
# schedule the system to wake from suspend to run atd jobs.

# To activate this example symlink it to /etc/pm/sleep.d

import sys
import time
import subprocess
import os

STORAGEDIR="%s/%s/storage" % (os.environ["PM_UTILS_RUNDIR"], os.environ["STASHNAME"])

def first_in_at_queue():
    first = None
    atq = subprocess.Popen(["atq"], stdout=subprocess.PIPE).communicate()[0]
    for line in atq.split("\n"):
        if not line: continue
        qid, rest = line.split("\t")
        date, queue, user = rest.rsplit(' ', 2)
        t = time.mktime(time.strptime(date, "%a %b %d %H:%M:%S %Y"))
        if first is None:
            first = t
        elif t < first:
            first = t
    return first

def suspend():
    first = first_in_at_queue()
    if first is None: return
    now = time.time()
    # Wake up 2 seconds after, so that atd -s runs pending jobs right away
    delay = first - now - +2
    if delay < 15: delay = 15
    subprocess.check_call(["rtcwake", "-m", "no", "-s", str(int(delay))])
    print "Wakeup scheduled in %d seconds" % delay

def resume():
    # Touch last-resume flagfile
    open(STORAGEDIR+"/last-resume", "w").close()

    if subprocess.call(["om", "resume-reason", "contains", "EINT09_PMU:rtc_alarm"]) == 0:
        print "Running atd -s"
        subprocess.check_call(["atd", "-s"])

if sys.argv[1] in ["hibernate", "suspend"]:
    suspend()
elif sys.argv[1] in ["thaw", "resume"]:
    resume()
else:
    sys.exit(254)

sys.exit(0)
