#!/bin/sh
#
# cpuspeed	Run dynamic CPU speed daemon
#
# chkconfig: 12345 01 99
# description:  The CPUSpeed daemon dynamically changes clock speeds \
#       and / or voltages of CPUs supported by the kernel cpufreq \
#       driver to minimize power consumption and temperature while \
#       still allowing the CPU to run at full speed when needed. \
#       The daemon can monitor CPU temperature and lower the CPU's \
#       speed if it gets too hot. The daemon can monitor a mobile \
#       system's AC adapter and minimize speed if it is disconnected \
#       or maximize speed if it is connected. \
#       \
#       This program is very useful for prolonging battery life on \
#       mobile systems and preventing system lockups and shutdowns \
#       on systems without adequate cooling.
# processname: cpuspeed
# config: /etc/sysconfig/cpuspeed

# Source function library.
. /etc/rc.d/init.d/functions

[ -f /sbin/cpuspeed ] || exit 0

prog="cpuspeed"

# Get config.
if [ -f /etc/sysconfig/cpuspeed ]; then
        . /etc/sysconfig/cpuspeed
fi

LOCKFILE=/var/lock/subsys/cpuspeed

start() {
    # make sure the userspace CPUFreq governor module is loaded
    /sbin/modprobe -q cpufreq_userspace

    if [ ! -f /sys/devices/system/cpu/cpu0/cpufreq/scaling_driver ]
    then
        if  [ -n "$DRIVER" ]
        then
            # attempt to load scaling_driver if not loaded but it is specified in config
            /sbin/modprobe -q $DRIVER
        else
            # if driver not loaded and not specified in config try to load default list
            #FIXME
            for i in powernow-k8 powernow-k7 powernow-k6 speedstep-ich speedstep-centrino p4-clockmod cpufreq-nforce2
            do
                /sbin/modprobe -q $i && break
            done
        fi
    fi

    #abort cpuspeed without FAILED message if unable to load a driver
    [ ! -f /sys/devices/system/cpu/cpu0/cpufreq/scaling_driver ] && return 0

    echo -n $"Starting $prog: " 
    [ -n "$DRIVER" ] && /sbin/modprobe $DRIVER
    start_daemon --lockfile "$LOCKFILE" --expect-user root -- cpuspeed -d $OPTS
    RETVAL=$?
    return $RETVAL
}

stop() {
    echo -n $"Stopping $prog: "
    stop_daemon -USR1 -- cpuspeed
    stop_daemon --lockfile "$LOCKFILE" --expect-user root -- cpuspeed
    RETVAL=$?
    return $RETVAL
}

case "$1" in
	start)
	    start
	    ;;
	
	stop)
	    stop
	    ;;
	
	status)
	    status cpuspeed
	    ;;
	restart)
	    stop
	    start
	    ;;

	condstop)
		if [ -e "$LOCKFILE" ]; then
			stop
		fi
		;;

	condrestart)
	    if test "x`pidof cpuspeed`" != x; then
		stop
		start
	    fi
	    ;;
	
	*)
	    echo $"Usage: $0 {start|stop|restart|condstop|condrestart|status}"
	    exit 1

esac

exit $RETVAL
