#!/bin/bash

# Script to suspend the laptop to disk when the battery is nearly empty
# Various bits and pieces borrowed from various ACPI scripts
#
# 25 Jan 2006
# Martin Leopold <leopold@diku.dk>
#
# Arg1 is ?
# Arg2 is the name of the battery signalling events
# Executed on "battery"

BATT_INFO=/proc/acpi/battery/$2/info
BATT_STATE=/proc/acpi/battery/$2/state
BATT_ALARM=/proc/acpi/battery/$2/alarm
IBM_BEEP_DEVICE=/proc/acpi/ibm/beep

WARN_BEEP=2
LOW_BEEP=9
AC_BEEP=6

REMAINING=`cat $BATT_STATE | grep "remaining capacity:" | sed  "s/.* \([0-9][0-9]* \).*/\1/" `
DESIGN_WARN=`cat $BATT_INFO | grep "design capacity warning:" | sed  "s/.* \([0-9][0-9]* \).*/\1/" `
DESIGN_LOW=`cat $BATT_INFO | grep "design capacity low:" | sed  "s/.* \([0-9][0-9]* \).*/\1/" `
ALARM=`cat $BATT_ALARM | grep "alarm:" | sed  "s/.* \([0-9][0-9]* \).*/\1/" `
HIBERNATE_CAPACITY=$(( 2*$DESIGN_LOW ))

echo Remain: $REMAINING, Low: $DESIGN_LOW Warn: $DESIGN_WARN Alarm: $ALARM Hibernate: $HIBERNATE_CAPACITY

status=`/usr/bin/awk '/^state: / { print $2 }' /proc/acpi/ac_adapter/AC/state`

ACTION="`cat $BATT_STATE | grep charging | cut -c 26-`"
if [[ $ACTION -eq "discharging" ]]
then
   if(( $REMAINING < $DESIGN_WARN && $REMAINING > $DESIGN_LOW))
   then
       echo $BEEP_WARN > $IBM_BEEP
   fi
   if(( $REMAINING < $HIBERNATE_CAPACITY))
   then
       echo $BEEP_LOW > $IBM_BEEP
       /etc/acpi/hibernate.sh
   fi
fi

