#!/bin/sh
# Startup script for cpuspeed
#
# chkconfig: 12345 06 99
# description: Run dynamic CPU speed daemon

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

[ -f /usr/sbin/cpuspeed ] || exit 5

prog="cpuspeed"

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

start() {
    if [ ! -f /var/lock/subsys/cpuspeed ]; then
	# Load powersave governor so it can be switched to via gnome applet
        /sbin/modprobe cpufreq_powersave 2> /dev/null
        cpu_vendor=$(awk '/vendor_id/{print $3}' /proc/cpuinfo | tail -n 1)
        cpu_family=$(awk '/cpu family/{print $4}' /proc/cpuinfo | tail -n 1)
        # Try loading powernow-k8 if this is an AMD processor,
        # family 7 or greater (Athlon XP/MP was family 6)
        if [ "$cpu_vendor" == AuthenticAMD ] && [ "$cpu_family" -ge 7 ]; then
          pk8m=$(/sbin/modinfo powernow-k8 > /dev/null 2>&1)
          if [ "$?" -eq 0 ]; then
            /sbin/modprobe powernow-k8 2> /dev/null
            [ -d ${cpu0freqd} ] || /sbin/modprobe -r powernow-k8 2> /dev/null
          fi
        fi
        # If not loaded, abort cpuspeed without [FAILED] message
        [ ! -f /sys/devices/system/cpu/cpu0/cpufreq/scaling_driver ] &&  return 0

        echo -n $"Starting $prog: "

        daemon cpuspeed -d $OPTS
        RETVAL=$?
        echo
        [ $RETVAL = 0 ] && touch /var/lock/subsys/cpuspeed
    else
        return 0
    fi
    return $RETVAL
}

stop() {
    if test "x`pidof cpuspeed`" != x; then
		echo -n $"Stopping $prog: "
		killproc cpuspeed -INT
		sleep 1
		echo
    fi
    if test "x`pidof cpuspeed`" != x; then
		killproc cpuspeed
    fi
    RETVAL=$?
    [ $RETVAL = 0 ] && rm -f /var/lock/subsys/cpuspeed
    return $RETVAL
}

case "$1" in
	start)
	    start
	    ;;

	stop)
	    stop
	    ;;

	status)
	    status cpuspeed
	    ;;
	restart)
	    stop
	    start
	    ;;
	condrestart)
	    if test "x`pidof cpuspeed`" != x; then
		stop
		start
	    fi
	    ;;

	*)
	    echo $"Usage: $0 {start|stop|restart|condrestart|status}"
	    exit 3

esac

exit $RETVAL
