#!/bin/sh

set -eu

DESC="Ubuntustudio Controls"

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

ENABLE="true"
NO_TURBO="0"
GOVERNOR="ondemand"

# we should check for the availablity of any setting we wish to change
check_turbo_avail() {
	info="/sys/devices/system/cpu/intel_pstate/no_turbo"
	if [ -f $info ]; then
		return 0;
	fi
	return 1;
}

# any setting in this file will override the above defaults.
# ubuntustudio-controls will normally write the defaults file
if [ -f /etc/default/ubuntustudio ] ; then
	. /etc/default/ubuntustudio
fi

# if not enabled then exit gracefully
[ "$ENABLE" = "true" ] || exit 0
RETVAL=0

logger "${DESC}: Setting system settings"
if check_turbo_avail ; then
	logger "${DESC}: Set no_turbo ${NO_TURBO}"
	echo "${NO_TURBO}" | tee /sys/devices/system/cpu/intel_pstate/no_turbo || \
		RETVAL=$?
	logger "${DESC}: ${RETVAL} "
else
	logger "${DESC}: turbo/boost not available"
fi

AVAILABLE="/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors"
[ -f $AVAILABLE ] || exit 0
read governors < $AVAILABLE

case "$GOVERNOR" in
  performance)
    case $governors in
      *performance*)
        GOVERNOR="performance"
        ;;
      *)
        exit 0
        ;;
    esac
    ;;
  *)
    case $governors in
      *ondemand*)
        GOVERNOR="ondemand"
        ;;
      *powersave*)
        GOVERNOR="powersave"
        ;;
      *)
        exit 0
        ;;
    esac
  ;;
esac

logger "${DESC}: Using ${GOVERNOR} governor"

for CPUFREQ in /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
  do
		logger "${DESC}: setting ${GOVERNOR} for ${CPUFREQ}"
    [ -f $CPUFREQ ] || continue
    echo -n $GOVERNOR > $CPUFREQ
  done
logger "${DESC}: Governor set finished"
exit 0

