#! /bin/bash

# Automatically disable laptop mode when the battery almost runs out.

BATT_INFO=/proc/acpi/battery/$2/state

if [[ -f /proc/sys/vm/laptop_mode ]]
then
   LM=`cat /proc/sys/vm/laptop_mode`
   if [[ $LM -gt 0 ]]
   then
     if [[ -f $BATT_INFO ]]
     then
	# Source the config file only now that we know we need
	if [ -f /etc/default/laptop-mode ] ; then
		# Debian
		. /etc/default/laptop-mode
	elif [ -f /etc/sysconfig/laptop-mode ] ; then
		# Others
        	. /etc/sysconfig/laptop-mode
	fi
	MINIMUM_BATTERY_MINUTES=${MINIMUM_BATTERY_MINUTES:-'10'}

        ACTION="`cat $BATT_INFO | grep charging | cut -c 26-`"
        if [[ ACTION -eq "discharging" ]]
        then
		PRESENT_RATE=`cat $BATT_INFO | grep "present rate:" | sed  "s/.* \([0-9][0-9]* \).*/\1/" `
		REMAINING=`cat $BATT_INFO | grep "remaining capacity:" | sed  "s/.* \([0-9][0-9]* \).*/\1/" `
        fi
        if (($REMAINING * 60 / $PRESENT_RATE < $MINUMUM_BATTERY_MINUTES))
        then
		/sbin/laptop_mode stop
        fi
     else
        logger -p daemon.warning "You are using laptop mode and your battery interface $BATT_INFO is missing. This may lead to loss of data when the battery runs out. Check kernel ACPI support and /proc/acpi/battery folder, and edit /etc/acpi/battery.sh to set BATT_INFO to the correct path."
     fi
   fi
fi
