#!/bin/bash
# RC.CPUFREQ SCRIPT FOR SLACKWARE
# Created by Robert Delahunt
# 
# This script is used to make it slightly easier to control Linux
# Kernel 2.6.x CPU Frequency scaling from the shell, and possibly
# to allow inclusion into Slackware's init scripts.
# 
# This is a gift for Slackware, no rights retained by author

# The location of the Scaling Governor:
SCG1="/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor"
SCG2="/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor"
# Default governor you want.  Valid entries:
# ondemand | powersave | performance | conservative | auto
# All are stock CPUFREQ values except auto, which tries to
# set powersave if running on batteries or ondemand if not.
DEFAULT="conservative"
# Where to detect if the battery is discharging.
# If your laptop or /proc is different, please set it.
PABB="/proc/acpi/battery/BAT1/state"

# Let's make sure our files exist:
if [ ! -r $SCG1 ]; then
   echo "For some reason, CPU Frequency Scaling is not detected"
   echo "in " $SCG ".... Exiting...."
   exit 1
fi
# Make sure we can read status if in auto mode....
if [ $1 == "auto" ]; then
   if [ ! -r $PABB ]; then
      echo $PABB "is not a valid location to read battery status."
      echo "Reverting to ondemand mode...."
      $0 ondemand
   fi
fi

# Ok, let's make sure they're calling this file properly,
# and if they are, just set what they asked for.
case "$1" in
performance|conservative|ondemand|userspace|powersave)
# This is easy: they picked a valid setting
   echo "Setting CPU Frequency Scaling mode " $1
   echo $1 > $SCG1
   echo $1 > $SCG2
;;
status)
  echo "Current CPU Frequency Scaling Mode:" \
     `cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor`
;;
auto)
   echo "Attempting automatic runtime...."
   # This might be ugly, but I'm no scripting expert lol
   STATUS=`grep "charging state" $PABB | awk '{print $3}'`
   if [ $STATUS == "discharging" ]; then
      echo powersave > $SCG1
      echo powersave > $SCG2
   else
      echo ondemand > $SCG1
      echo ondemand > $SCG2
   fi
   $0 status
;;
start)
   echo $0 $DEFAULT
   $0 $DEFAULT
;;
stop)
   echo "STOP signalled, switching to performance mode..."
   $0 performance
;;
*)
   echo "USAGE: "
   echo $0 "performance|ondemand|conservative|powersave|status|auto|stop"
   $0 status
   exit
esac
