#!/bin/sh
### BEGIN INIT INFO
# Provides:          raspi-config
# Required-Start: udev mountkernfs $remote_fs
# Required-Stop:
# Default-Start: S 2 3 4 5
# Default-Stop:
# Short-Description: Switch to ondemand cpu governor (unless shift key is pressed)
# Description:
### END INIT INFO

. /lib/lsb/init-functions

if [ -f /etc/default/cpu_governor ]; then
  . /etc/default/cpu_governor
fi

CPU_DEFAULT_GOVERNOR="${CPU_DEFAULT_GOVERNOR:-ondemand}"
CPU_ONDEMAND_UP_THRESHOLD="${CPU_ONDEMAND_UP_THRESHOLD:-50}"
CPU_ONDEMAND_SAMPLING_RATE="${CPU_ONDEMAND_SAMPLING_RATE:-100000}"
CPU_ONDEMAND_DOWN_SAMPLING_FACTOR="${CPU_ONDEMAND_DOWN_SAMPLING_FACTOR:-50}"
CPU_ONDEMAND_INCLUDE_IO_CALC="${CPU_ONDEMAND_INCLUDE_IO_CALC:-0}"

case "$1" in
  start)
    log_daemon_msg "Checking if shift key is held down"
    if [ -x /usr/sbin/thd ] && timeout 1 thd --dump /dev/input/event* | grep -q "LEFTSHIFT\|RIGHTSHIFT"; then
      printf " Yes. Not enabling $CPU_DEFAULT_GOVERNOR scaling governor"
      log_end_msg 0
    else
      printf " No. Switching to $CPU_DEFAULT_GOVERNOR scaling governor"
      SYS_CPUFREQ_GOVERNOR=/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
      if [ -e $SYS_CPUFREQ_GOVERNOR ]; then
        for cpu_core in /sys/devices/system/cpu/cpu?/cpufreq/scaling_governor ; do
          echo "$CPU_DEFAULT_GOVERNOR" > $cpu_core
        done
        if [ "$CPU_DEFAULT_GOVERNOR" = "ondemand" ]; then
          echo "$CPU_ONDEMAND_UP_THRESHOLD" > /sys/devices/system/cpu/cpufreq/ondemand/up_threshold
          echo "$CPU_ONDEMAND_SAMPLING_RATE" > /sys/devices/system/cpu/cpufreq/ondemand/sampling_rate
          echo "$CPU_ONDEMAND_DOWN_SAMPLING_FACTOR" > /sys/devices/system/cpu/cpufreq/ondemand/sampling_down_factor
          echo "$CPU_ONDEMAND_INCLUDE_IO_CALC" > /sys/devices/system/cpu/cpufreq/ondemand/io_is_busy
        fi
      fi
      log_end_msg 0
    fi
    ;;
  stop)
    ;;
  restart)
    ;;
  force-reload)
    ;;
  *)
    echo "Usage: $0 start" >&2
    exit 3
    ;;
esac
