#! /bin/sh

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/powernowd
NAME=powernowd
DESC=powernowd

test -x $DAEMON || exit 0

# create the file /etc/default/powernowd if you want to override the value of
# variable OPTIONS and change the default behavior of the daemon as launched

OPTIONS=""
[ -f /etc/default/$NAME ] && . /etc/default/$NAME

# Get lsb functions
. /lib/lsb/init-functions

set -e

load_modules() {
        #build a list of current modules so we don't load a module twice
        LIST=`/sbin/lsmod|awk '!/Module/ {print $1}'`
        
        #get list of available modules
        LOC="/lib/modules/`uname -r`/kernel/drivers/cpufreq"
        if [ -d $LOC ]; then
          MODAVAIL=`( find $LOC -type f -name "*.o" -printf "basename %f .o\n"; \
                   find $LOC -type f -name "*.ko" -printf "basename %f .ko\n" ) | /bin/sh`
        else
          MODAVAIL=""
        fi

        
        #echo "Loading cpufreq modules:"
        for mod in $MODAVAIL; do
        #        echo "     $mod"
                echo $LIST| grep -q -w "$mod" || modprobe $mod >/dev/null || /bin/true
        done

        # now lets load the driver
        
        #cpufreq is built in on powerpc; just return
        if [ "`uname -m`" = "ppc" ]; then
                return 0
        fi

        if [ ! $FREQDRIVER = "" ]; then 
                modprobe $FREQDRIVER||true
        fi

        if [ "`uname -m`" = "x86_64" ]; then 
                modprobe powernow-k8 >/dev/null 2>&1||true
        fi

        if [ ! -f /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor ]; then
                modprobe acpi > /dev/null 2>&1|| true
        fi
}

check_kernel() {
	CPUFREQ=/sys/devices/system/cpu/cpu0/cpufreq

	if [ -f $CPUFREQ/scaling_governor ] && \
		[ -f $CPUFREQ/scaling_available_governors ] && \
		grep -q userspace $CPUFREQ/scaling_available_governors
	then
		return 0
	else
		return 1
	fi
}

start() {
	if check_kernel
	then
	#       echo "Starting $DESC: "
		start-stop-daemon --start --quiet --oknodo --exec $DAEMON -- $OPTIONS >/dev/null 2>&1|| return 1
	else
	#	echo "required sysfs objects not found!"
	#	echo -e "\tRead /usr/share/doc/powernowd/README.Debian for more information."
		return 0
	fi
}

case "$1" in
  start)
        [ -f /proc/modules ] && load_modules
        log_begin_msg "Starting $DESC... "
	start
        log_end_msg $?
	;;
  stop)
	log_begin_msg "Stopping $DESC: "
	start-stop-daemon --stop --quiet --oknodo --exec $DAEMON
	log_end_msg $?
	;;
  restart|force-reload)
        $0 stop
	sleep 1
	start
	echo "$NAME."
	;;
  *)
	N=/etc/init.d/$NAME
	log_success_msg "Usage: $N {start|stop|restart|force-reload}" >&2
	exit 1
	;;
esac

exit 0
