#! /bin/sh
### BEGIN INIT INFO
# Provides:          powersaved
# Required-Start:    $remote_fs dbus hal
# Required-Stop:     $remote_fs dbus hal
# Should-Start:	     $syslog acpid loadcpufreq cpufrequtils
# Should-Stop:       $syslog acpid
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: power management daemon
# Description:       Support for ACPI, APM and CPU frequency scaling.
#                    Detects HW support for mentioned systems and optimises 
#                    power consumption accordingly.
### END INIT INFO
#
# Author: Michael Biebl <biebl@debian.org>.
#

DAEMON=/usr/sbin/powersaved
DAEMON_OPTS="-f /var/run/acpid.socket"
NAME=powersaved
DESC="power management daemon"
CONFIG=/etc/powersave
POWERSAVE_BIN=/usr/bin/powersave
ACPID_BIN=/usr/sbin/acpid

test -x $DAEMON || exit 0
test -x $POWERSAVE_BIN || exit 0
test -x /usr/bin/logger && LOGGER="/usr/bin/logger -t powersaved" || LOGGER="echo"

. /lib/lsb/init-functions

if [ -r $CONFIG ] ; then
	. $CONFIG/common
	. $CONFIG/thermal
fi


check_apm_acpi()
{
	ACPI_APM=`$POWERSAVE_BIN --apm-acpi`
	
	if [ "$ACPI_APM" = "ACPI" ] ; then
		# set thermal polling frequency
		# this should be managed by the daemon later
		if [ "$THERMAL_POLLING_FREQUENCY" != "0" ];then
			[ -z "$THERMAL_POLLING_FREQUENCY" ] && THERMAL_POLLING_FREQUENCY=2
                       	for x in /proc/acpi/thermal_zone/*; do
				[ -w $x/polling_frequency ] && echo "$THERMAL_POLLING_FREQUENCY" >$x/polling_frequency
			done
		fi

		if ! [ `pidof  $ACPID_BIN` ] ; then
			log_end_msg 1
			$LOGGER "WARN: Service powersaved skipped. You have to install and start acpid before powersaved"
			echo "##########################################################"
			echo "# ACPI system but acpid not running.                     #"
			echo "# Please install acpid package, then restart powersaved! #"
			echo "##########################################################"
			exit 7
		fi
		$LOGGER "Starting powersaved with ACPI support"
	elif [ "$ACPI_APM" = "APM" ] ; then
		$LOGGER "Starting powersaved with APM support"
	else
		$LOGGER "Starting powersaved without APM and ACPI support"
	fi
}

case "$1" in
  start)
  	log_daemon_msg "Starting $DESC" $NAME
	check_apm_acpi
	start-stop-daemon --start --quiet --pidfile /var/run/$NAME.pid \
		--oknodo --exec $DAEMON -- -d $DAEMON_OPTS
	log_end_msg $?
	;;
  stop)
	log_daemon_msg "Stopping $DESC" $NAME
	start-stop-daemon --stop --retry 5 --quiet --pidfile /var/run/$NAME.pid \
		--oknodo --exec $DAEMON
	log_end_msg $?
	;;
  reload|force-reload)
	log_begin_msg "Reloading $DESC configuration files"
	start-stop-daemon --stop --signal 1 --quiet --pidfile \
		/var/run/$NAME.pid --exec $DAEMON
	log_end_msg $?
  ;;
  restart)
	$0 stop
        $0 start
	;;
  *)
	N=/etc/init.d/$NAME
	echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
	exit 1
	;;
esac

exit 0
