#!/bin/sh

[ -x /usr/bin/cpupower ] || exit $NA

CPUPOWER_GOVERNOR_AC=${CPUPOWER_GOVERNOR_AC:-ondemand}
CPUPOWER_GOVERNOR_BAT=${CPUPOWER_GOVERNOR_BAT:-conservative}

help() {
    cat <<EOF
--------
$0: Select cpupower frequency governor.

Parameters:
CPUPOWER_GOVERNOR_AC = Governor to use on AC.
Defaults to ondemand.

CPUPOWER_GOVERNOR_BAT = Governor to use on battery.
Defaults to conservative.

EOF
}

cpupow() {
    printf "Setting cpupower frequency governor to %s..." "$1"

  if grep -qw "$1" /sys/devices/system/cpu/cpu*/cpufreq/scaling_available_governors || modprobe -q "cpufreq_$1"; then
    for cpu in $(sed -ne 's/^processor.* \([0-9]\+\)$/\1/p' /proc/cpuinfo); do
      if ! cpupower -c $cpu frequency-set -g $1; then
        echo "CPU $cpu failed."
        return 1
      fi
    done
    echo Done.
  else
    echo "Cannot load module. Failed."
    return 1
  fi
}

case $1 in
    true) cpupow "$CPUPOWER_GOVERNOR_BAT" ;;
    false) cpupow "$CPUPOWER_GOVERNOR_AC" ;;
    help) help;;
    *) exit $NA ;;
esac

exit 0
