#!/bin/sh
# 
# Helper script for the FreeBSD devd.
# Trigger warnings and force a clean shutdown when the laptop battery is 
# running low.
#
# Usage:
#    Put these lines into your /etc/devd.conf and start devd from /etc/rc.conf
#
#      # Warnings and emergency shutdown if battery is running low.
#      notify 10 {
#              match "system"          "ACPI";
#              match "subsystem"       "CMBAT";
#              action "/etc/rc.d/battery";
#      };
#
# Copyright (c) 2004 Michael Lestinsky
# Copyright (c) 2006 Beat Gätzi
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY MICHAEL LESTINSKY ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL MICHAEL LESTINSKY BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.

# ACPI battery states
STATE_DISCHARG=1
STATE_CHARGING=2
STATE_LOW=5
STATE_CRITICAL=4
STATE_NOTPRESENT=7

level=`/sbin/sysctl -n hw.acpi.battery.life`
state=`/sbin/sysctl -n hw.acpi.battery.state`
warn_level=5
shutdown_delay=60

shutdown="/sbin/shutdown -p +1"
log="/usr/bin/logger -t battery -p daemon.notice"
wall="/usr/bin/wall"

if [ $level -le $warn_level ] && [ $state -eq  $STATE_DISCHARG ] ; then
	time=`/sbin/sysctl -n hw.acpi.battery.time`
	$wall <<EOF
Battery is running low:	$level % 
estimated lifetime:	$time min
Emergency shutdown in $shutdown_delay sec
EOF

	sleep $shutdown_delay

	state=`/sbin/sysctl -n hw.acpi.battery.state`
	if [ $state -ne $STATE_CHARGING ] ; then
		$log "Battery running low. Shutting down"
		$wall <<EOF
Battery is running low: $level%
Emergency shutdown initiated.
EOF
		$shutdown
	fi
fi
