#! /bin/bash
# Copyright (c) 2002 SuSE Linux AG, Nuernberg, Germany.
# All rights reserved.
#
# Author: Thomas Renninger <trenn@suse.de, mail@renninger.de>
#
# /etc/init.d/powersave
#   and its symbolic link
# /usr/sbin/rcpowersave
#
# LSB compliant service control script; see http://www.linuxbase.org/spec/
# 
# Should start contains acpid apmd and cpufreqd, so that I can check
# whether they are running and whether this script should fail
# apmd and cpufreqd should never run together with this service

### BEGIN INIT INFO
# Provides:                   powersaved
# Required-Start:             $remote_fs
# X-UnitedLinux-Should-Start: $syslog acpid apmd cpufreqd
# Required-Stop:              $remote_fs
# X-UnitedLinux-Should-Stop:  $syslog 
# Default-Start:              2 3 5
# Default-Stop:               0 1 6
# Short-Description: optimises power consumption, specially for laptops
# Description:       supports acpi apm and cpufrequency scaling
#	detects HW support for mentioned systems and optimises power consumption
#	accordingly. 
#       Back-end to the YaST2 power management configuration module
#	Additionally this start script loads all needed modules
#       for cpufrequency scaling and acpi support

### END INIT INFO

# Check for missing binaries (stale symlinks should not happen)
POWERSAVED_BIN=/usr/sbin/powersaved
POWERSAVE_BIN=/usr/bin/powersave
ACPID_BIN=/usr/sbin/acpid
test -x $POWERSAVED_BIN || exit 5
# Check for existence of needed config file and read it

# ToDo set it on the real directory 
POWERSAVED_CONFIG=/etc/sysconfig/powersave

test -r $POWERSAVED_CONFIG || exit 6
. $POWERSAVED_CONFIG/common
. $POWERSAVED_CONFIG/cpufreq
if test -e /etc/sysconfig/security; then
 . /etc/sysconfig/security
fi

LOGGER="/bin/logger -t rcpowersaved"
# Shell functions sourced from /etc/rc.status:
#      rc_check         check and set local and overall rc status
#      rc_status        check and set local and overall rc status
#      rc_status -v     ditto but be verbose in local rc status
#      rc_status -v -r  ditto and clear the local rc status
#      rc_status -s     display "skipped" and exit with status 3
#      rc_status -u     display "unused" and exit with status 3
#      rc_failed        set local and overall rc status to failed
#      rc_failed <num>  set local and overall rc status to <num>
#      rc_reset         clear local rc status (overall remains)
#      rc_exit          exit appropriate to overall rc status
#      rc_active	checks whether a service is activated by symlinks
#      rc_splash arg    sets the boot splash screen to arg (if active)
. /etc/rc.status

# Reset status of this service
rc_reset

# Return values acc. to LSB for all commands but status:
# 0	  - success
# 1       - generic or unspecified error
# 2       - invalid or excess argument(s)
# 3       - unimplemented feature (e.g. "reload")
# 4       - user had insufficient privileges
# 5       - program is not installed
# 6       - program is not configured
# 7       - program is not running
# 8--199  - reserved (8--99 LSB, 100--149 distrib, 150--199 appl)
# 
# Note that starting an already running service, stopping
# or restarting a not-running service as well as the restart
# with force-reload (in case signaling is not supported) are
# considered a success.


# maybe I could check for apm, acpi and cpufreq
# if nothing is there it makes no sense to start the program
# but this is nasty because of different kernel
# implementations and therefore different file locations

POWERSAVED_OPTS=""

case "$1" in
	start)
		checkproc $POWERSAVED_BIN
		if [ $? = 0 ]; then
		    echo -n "daemon already running"
		    rc_status -v
		    rc_exit
		elif [ -e /var/run/powersaved.pid ];then 
		    rm -f  /var/run/powersaved.pid&> /dev/null
		fi;
		checkproc "cpufreqd" &>/dev/null
		if [ $? = 0 ]; then
		    echo -n "cpufreqd already running, stop it first and restart service"
		    rc_status -s
		    rc_exit
		fi

		ACPI_APM=`$POWERSAVE_BIN --apm-acpi`
		if [ "$ACPI_APM" = "ACPI" ]; then
		    pidof $ACPID_BIN >/dev/null
		    ACPID_NOT_RUNNING=$?
		    # if acpid is not there we need access to /proc/acpi/event
		    if [ $ACPID_NOT_RUNNING = 1 ];then
			####### check progs accessing /proc/acpi/event ##########
			EXIT=0;N=0;
			for X in $(fuser /proc/acpi/event);do
			    test $((N++)) -lt 1 && EXIT=1 && echo -n "Process " && continue; 
			    while read a b; do 
				if [ $a = Name: ]; then 
				    echo -n "$b "; 
				    break; 
				fi; 
			    done < /proc/$X/status ;
			done
			if [ $EXIT = 1 ]; then 
			    echo "is accessing /proc/acpi/event."
			    echo -n "Stop it first and restart powersave service."
			    rc_status -s
			    rc_exit
			fi
                        ####### check progs accessing /proc/acpi/event ##########
			# load ACPI modules
			echo -n "loading ACPI modules ("
			for m in $POWERSAVE_ACPI_MODULES; do
			    grep -wq $m /proc/modules || { modprobe -s $m && echo -n "$m "; }
			done
			echo -n ") "
			rc_status -v
		        # load ACPI modules end 
			# Start acpid and let it ignore all ACPI events -> powersave handles them (default)
			if [ "$POWERSAVED_START_ACPID" = "yes" ] && [ -x $ACPID_BIN ];then
			    ACCESS_PROC_EVENTS=" (accessing ACPI events over acpid) "
			    $ACPID_BIN -c /etc/acpi/events.ignore
			else
			    ACCESS_PROC_EVENTS=" (directly accessing /proc/acpi/events) "
			fi
     		        # set thermal polling frequency
		        # this should be managed by the daemon later
			for x in /proc/acpi/thermal_zone/*; do
			    [ -w $x/polling_frequency ] && echo 5 >$x/polling_frequency
			done
		    # acpid already running -> will probably handle ACPI events itself -> exit
		    else
			$LOGGER "acpid already running, please set this service to off. The acpid should be started by the powersaved"
			echo "acpid already running, but should be started by powersaved."
			echo -n "Please set acpid service to off or stop it manually"
			rc_status -s
			rc_exit
		    fi
		    
		elif [ "$ACPI_APM" = "APM" ]; then
		    # check whether apmd is already running
		    checkproc "apmd" &>/dev/null
		    if [ $? = 0 ];then
			echo -n "APM daemon is already running, stop it first and restart service"
			rc_status -s
			rc_exit
		    fi
		    echo -n "This machine supports APM "
		
		#### when neither APM nor ACPI is found, skip, powersaved would have,
		#### no functionality, as cpufreq is probably not supported as well
		else
		    $LOGGER "INFO: Your system does neither support ACPI nor APM. \
the powersave service does not provide any features for this machine, therefore the service is skipped."
		    rc_status -s
		fi 

		CPUFREQ_MODULES="speedstep_centrino speedstep_ich powernow_k8 powernow_k7 powernow_k6 longrun longhaul acpi"
		CPUFREQ_MODULES_GREP="^speedstep_centrino\|^speedstep_ich\|^powernow_k8\|^powernow_k7\|^powernow_k6\|^longrun\|^longhaul\|^acpi"

		###### load CPUFREQ modules############
		# module specfied in sysconfig.cpufreq?
		if [ "$POWERSAVE_CPUFREQD_MODULE" != "off" ]; then
			# test for already loaded modules
			ALREADY_LOADED_MODS=`grep $CPUFREQ_MODULES_GREP /proc/modules`
			if [ "$POWERSAVE_CPUFREQD_MODULE" ]; then
				modprobe -q $POWERSAVE_CPUFREQD_MODULE $POWERSAVE_CPUFREQD_MODULE_OPTS &>/dev/null
				RETVAL=$?
			# try to load one of the modules we know
			elif [ -z "$ALREADY_LOADED_MODS" ] ; then 
				for MODULE in $CPUFREQ_MODULES; do
					modprobe $MODULE &>/dev/null
					RETVAL=$?
					[ "$RETVAL" = 0 ] && break
				done
				# skip if no module could be loaded!
				if [ "$RETVAL" != 0 ]; then
					$LOGGER "CPU frequency scaling is not supported by your processor."
					$LOGGER "enter 'POWERSAVE_CPUFREQD_MODULE=off' in $POWERSAVED_CONFIG/cpufreq to avoid this warning."
				else
					$LOGGER "enter '$MODULE' into POWERSAVE_CPUFREQD_MODULE in $POWERSAVED_CONFIG/cpufreq."
					$LOGGER "this will speed up starting powersaved and avoid unnecessary warnings in syslog."
				fi
			fi
			# test for cpufreq_userspace if not compiled in kernel!
			[ "$RETVAL" = 0 ] && modprobe cpufreq_userspace &>/dev/null
			# wait for modules to be loaded
			usleep 10000
		fi
		###### load CPUFREQ modules############

		#### Check for access permissions ####
		if [ "$POWERSAVED_SECURITY" != "root" ]; then
			POWERSAVED_OPTS="$POWERSAVED_OPTS -a $POWERSAVED_SECURITY"
		fi
		echo -n "Starting powersaved $ACCESS_PROC_EVENTS"
		[ $POWERSAVED_DEBUG ] && POWERSAVED_OPTS="$POWERSAVED_OPTS -v $POWERSAVED_DEBUG"
		startproc $POWERSAVED_BIN -d -x /usr/lib/powersave/scripts $POWERSAVED_OPTS
		rc_status -v
		;;
	stop)   
	        if [ "$POWERSAVED_START_ACPID" = "yes" ] && [ -x $ACPID_BIN ];then
		    echo -n "Shutting down acpid"
		    killproc -TERM /usr/sbin/acpid
		    rc_status -v
		fi 
		echo -n "Shutting down powersaved "
		killproc -TERM $POWERSAVED_BIN
		rc_status -v
		echo -n "Unloading ACPI modules ("
		for m in $POWERSAVE_ACPI_MODULES; do
			for n in $POWERSAVE_ACPI_MODULES_NOT_TO_UNLOAD; do
				test "$m" = "$n" && continue 2
			done
			modprobe -r $m 2>/dev/null && echo -n "$m "; rc_status
		done
		echo -n ") "
		rc_status -v
		;;
	try-restart)
	        $0 status
		if test $? = 0; then
			$0 restart
		else
			rc_reset        # Not running is not a failure.
		fi
		rc_status
		;;
	restart)
		$0 stop
		$0 start
		rc_status
		;;
	force-reload|reload)
		echo -n "Reload service powersaved "
		killproc -HUP $POWERSAVED_BIN
		rc_status -v
		;;
	status)
		echo -n "Checking for service powersaved "
		checkproc $POWERSAVED_BIN
		rc_status -v
		;;
	*)
		echo "Usage: $0" \
		     "{start|stop|status|try-restart|restart|force-reload|reload}"
		exit 1
		;;
esac
rc_exit
