#!/bin/sh
# 
# Starts the powernowd daemon
#
# chkconfig: 345 66 34
# description: Controls the cpu frequency with powernowd
# processname: powernowd
#
# It unserstands "stop", "start", "restart", and these other commands:
#	"high"	kill daemon, set cpu to high speed.
#	"low" 	kill daemon, set cpu to low speed.
#
# config: /etc/sysconfig/powernowd
### BEGIN INIT INFO
# Provides:          powernowd
# Required-Start:    $syslog $remote_fs $time
# Required-Stop:     $syslog $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start powernowd .
### END INIT INFO

# Do not load RH compatibility interface.
WITHOUT_RC_COMPAT=1

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

OPTIONS=""
PROGNAME=powernowd
DAEMON=/usr/sbin/$PROGNAME
LOCKFILE=/var/lock/subsys/$PROGNAME
MODULE=cpufreq_userspace

test -x $DAEMON || exit 0
RETVAL=0

KERNEL_VER_MAJOR="`uname -r | cut -d. -f1`"
KERNEL_VER_MINOR="`uname -r | cut -d. -f2`"

if [ $KERNEL_VER_MAJOR -eq 2 ] && [ $KERNEL_VER_MINOR -ge 6 ] || \
    [ $KERNEL_VER_MAJOR -eq 3 ] && [ $KERNEL_VER_MINOR -ge 0 ] ; then
    /sbin/modinfo $MODULE &>/dev/null
    if [ "$?" != "0" ] ; then
	echo -n $"required $MODULE kernel module does not exist."; warning; echo
	exit 0
    fi
else
    echo -n $"running a v$KERNEL_VER_MAJOR.x kernel required."; warning; echo
    exit 0
fi

# Load config
SourceIfNotEmpty /etc/sysconfig/powernowd

load_module()
{
    
    if ! loaded=`lsmod | grep $MODULE`; then
    echo -n $"Loading $MODULE kernel module: "
    RET=0
    /sbin/modprobe $MODULE &>/dev/null
    RET=$?
    [ $RET -eq 0 ] && success || failure
    echo
    fi
}

start()
{
    load_module
    start_daemon --expect-user root \
	 --lockfile "$LOCKFILE" \
	 -- $DAEMON $OPTIONS
    RETVAL=$?
    return $RETVAL
}

stop()
{
    stop_daemon --expect-user root \
        --lockfile "$LOCKFILE" \
        -- $DAEMON
    RETVAL=$?
    return $RETVAL
}

low()
{
    stop
	for i in `/bin/ls /sys/devices/system/cpu/`; do 
	pushd . >& /dev/null
	cd /sys/devices/system/cpu/$i/cpufreq
	cat scaling_min_freq > scaling_setspeed
	popd >& /dev/null
    done
}

high()
{
    stop
    for i in `/bin/ls /sys/devices/system/cpu/`; do 
        pushd . >& /dev/null
        cd /sys/devices/system/cpu/$i/cpufreq
        cat scaling_max_freq > scaling_setspeed
        popd >& /dev/null
    done
}

restart()
{
    stop
    start
}

reload()
{
	stop_daemon --expect-user root -HUP -- $DAEMON
}

# See how we were called.
case "$1" in
    start)
    	start
	;;
    stop)
	stop
	;;
    low) 
	low
	;;
    high)
	high
	;;
    reload)
	reload
	;;
    restart)
	restart
	;;
    condrestart)
	if [ -f $LOCKFILE ]; then
	    restart
	fi
	;;
    status)
	status $PROGNAME
	;;
    *)
	msg_usage "${0##*/} {start|stop|low|high|restart|condrestart|status}"
	RETVAL=1
esac

exit $RETVAL
