#!/bin/sh
#
# APM wrapper script - Created Dec 2004 by Brendan Grieve (bundabrg)
# Version: 1.0.2
# Description
#  Executes the scripts in /etc/apm/wakeup.d when trying
#  to suspend the device. These scripts return the time
#  the device is allowed to suspend for in minutes.
#  The lowest one is is used.


# Version: 1.0.1
# Description:
#  Execute scripts in /etc/apm/suspend.d before a suspend, and
#  then execute scripts in /etc/apm/resume.d after a resume.
#  The scripts themselves are stored in /etc/apm/scripts.d and are
#  symlinked to in the suspend.d and resume.d directories 



APM=/usr/bin/apm.x
APMSLEEP=/usr/bin/apmsleep

if [ "$1" = "--suspend" -o "$1" = "-s" -o "$1" = "--su" ]; 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
  
  if [ "$TIME_LOW" = "0" ];then
    $APM --suspend
  else
    $APMSLEEP +0:$TIME_LOW
  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
