#!/bin/sh
#
# APM wrapper script - uses at/atd to enable wakeup alarms
# Based on wrapper script for apmsleep by Brendan Grieve (bundabrg)

APM=/usr/bin/apm.x
AT=/usr/bin/at

if [ \( "$1" = "--suspend" -o "$1" = "-s" -o "$1" = "--su" \) -a -f /var/run/atd.pid ]; then
  for I in /etc/apm/suspend.d/*; do
    # Check if the script is there.
    [ ! -f $I ] && continue
	                
    # Execute scripts.
    if [ -x $I ];then
      $I suspend
    fi
  done
	
  sleep 1
  # Look for next wakeup event
  TIME_LOW=0
  for i in /etc/apm/wakeup.d/*; do
    if [ ! -x "$i" ];then
      continue
    fi
    T=$($i)
    if [ "$T" = "" ]; then
      continue
    fi
    
    let T_T=T\<TIME_LOW
    if [ "$TIME_LOW" = "0" -o "$T_T" = "1" ];then
      TIME_LOW=$T
    fi
  done
  
  # Get a time stamp
  WAKE_TIME=$(date -d "+$TIME_LOW minutes")
  if [ -f ~/.kopi_next_alarm ]; then
    # See if the next kopi alarm is sooner
    TMP_TIME=$(cat ~/.kopi_next_alarm | head -1)
    if [ \( $(date -d "$TMP_TIME" +"%s") -gt $(date -d "$WAKE_TIME" +"%s") \) -o "$TIME_LOW" = "0" ]; then
      WAKE_TIME=$(date -d "$TMP_TIME")
      TIME_LOW="1"
    fi
  fi
  if [ -f ~/.kopi_suspend_alarm ]; then
    # See if a suspended kopi alarm is sooner
    TMP_TIME=$(cat ~/.kopi_suspend_alarm | head -1)
    if [ \( $(date -d "$TMP_TIME" +"%s") -gt $(date -d "$WAKE_TIME" +"%s") \) -o "$TIME_LOW" = "0" ]; then
      WAKE_TIME=$(date -d "$TMP_TIME")
      TIME_LOW="1"
    fi
  fi
  
  if [ "$TIME_LOW" = "0" ];then
    $APM --suspend
  else
    # this is a hack...! how else can atd be used to wake up without
    #  actually executing anything?
    if [ ! -f ~/.wakeup ]; then
      touch ~/.wakeup
    fi
    $AT -f ~/.wakeup "$(date -d "$WAKE_TIME" +"%Y-%m-%d %H:%M:%S")"
    echo "test"
    $APM --suspend
  fi

  for I in /etc/apm/resume.d/*; do                                             
    # Check if the script is there.                                             
    [ ! -f $I ] && continue                                                     
                                                                                          
    # Execute scripts.                                                          
    if [ -x $I ];then                                                           
      $I resume                                                                
    fi                                                                          
  done  

else
    $APM $@
fi
