#! /bin/sh
#
# Script to change do system side things for ubuntustudio-controls
#
#
GOVERNOR="ondemand"
NO_TURBO="0"

set_governors() {
  # do this here in case we hit exit 0 before the end
  echo "NO_TURBO=$NO_TURBO\n" > /etc/default/ubuntustudio
  echo "GOVERNOR=${GOVERNOR}\n" >> /etc/default/ubuntustudio
  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

	for CPUFREQ in /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
		do
			[ -f $CPUFREQ ] || continue
			echo -n $GOVERNOR > $CPUFREQ
		done
  #reswrite just in case we corrected something
  echo "NO_TURBO=$NO_TURBO\n" > /etc/default/ubuntustudio
  echo "GOVERNOR=${GOVERNOR}\n" >> /etc/default/ubuntustudio

}

# 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

case "$1" in
	performance)
    GOVERNOR="performance"
    set_governors
    ;;

	ondemand)
		GOVERNOR="ondemand"
    set_governors
		;;

	powersave)
    GOVERNOR="powersave"
    set_governors
    ;;

	fix)
		if [ -f /etc/security/limits.d/audio.conf.disabled ]; then
			mv /etc/security/limits.d/audio.conf.disabled /etc/security/limits.d/audio.conf
		elif ! [ -f /etc/security/limits.d/audio.conf ]; then
			cp /usr/share/ubuntustudio-controls/audio.conf /etc/security/limits.d/audio.conf
		fi
    if [ ${PKEXEC_UID} -gt 999 ]; then
      /usr/sbin/adduser `id -nu ${PKEXEC_UID}` audio
    fi
		;;

	boost)
		if [ -f /sys/devices/system/cpu/intel_pstate/no_turbo ]; then
			echo "NO_TURBO=0\n" > /etc/default/ubuntustudio
      echo "GOVERNOR=${GOVERNOR}" >> /etc/default/ubuntustudio
			echo "0" | tee /sys/devices/system/cpu/intel_pstate/no_turbo
		fi
		;;

	noboost)
		if [ -f /sys/devices/system/cpu/intel_pstate/no_turbo ]; then
			echo "NO_TURBO=1\n" > /etc/default/ubuntustudio
      echo "GOVERNOR=${GOVERNOR}" >> /etc/default/ubuntustudio
			echo "1" | tee /sys/devices/system/cpu/intel_pstate/no_turbo
		fi
		;;


	nosys)
		/etc/init.d/cron stop
		;;

	sys)
		/etc/init.d/cron start
		;;

	*)
	 exit 0
	 ;;

	esac
