#! /bin/sh

set -e

load_modules() {
        #stop the kernel printk'ing at all while we load.
        PRINTK=`cat /proc/sys/kernel/printk`
        [ "$VERBOSE" = no ] && echo "0 0 0 0" > /proc/sys/kernel/printk
        
        #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
        
        #cpufreq is built in on powerpc; just return
        if [ "`uname -m`" = "ppc" ]; then
                return 0
        fi


        #new style detection system
        if [ ! "$FREQDRIVER" = "" ]; then 
                modprobe "$FREQDRIVER"
        else
	        . /usr/share/powernowd/cpufreq-detect.sh
                [ ! -z "$MODULE" ] && (modprobe "$MODULE"||modprobe "$MODULE_FALLBACK")
        fi

        if [ "$USE_OLD_DETECT" = "fish" ]; then
        # now lets load the driver
        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
        fi
        echo "$PRINTK" > /proc/sys/kernel/printk
}

[ -f /proc/modules ] && load_modules

exit 0

