#!/bin/bash

# Copyright Jean-Philippe Guillemin <jpguillemin@sfr.fr>. This program is free software;
# you can redistribute it and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 of the License,
# or (at your option) any later version. Please take a look at http://www.gnu.org/copyleft/gpl.htm



# Version 2.0 - 01/06/2022


if [[ "$1" ]] ; then 
	case "$1" in
	'performance' | 'powersave' | 'ondemand' | 'conservative')
		echo "$1" | tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor 1> /dev/null 2> /dev/null
		echo "Enabled CPU frequency scaling governor:  $(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor)"
		;;
	*)
		echo "usage $0 conservative|ondemand|powersave|performance"
	esac
	exit
fi

# Take a look at "Xdialog" and use it instead of "dialog" in case X is running
if [[ "$DISPLAY" && "$(which Xdialog 2>&1 | grep -v "which: no")" ]]; then
	dialog="Xdialog --auto-placement --icon cpufreqconfig"
else
	dialog="dialog"
fi

# Gettext internationalization
export TEXTDOMAIN="cpufreqconfig"
export TEXTDOMAINDIR="/usr/share/locale"
. gettext.sh

# Path needs to be extended in case you're only half a root :)
export PATH="${PATH}:/usr/sbin:/sbin"

if [ "$(id -u)" != "0" ]; then
	$dialog --title "$(eval_gettext 'Root only')" --msgbox "$(eval_gettext 'You need to be root to run ') $(basename $0)" 8 65 
	exit
fi

governor=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor)
if [ "$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_driver 2> /dev/null)" = "intel_pstate" ]; then
export newgovernor=$(${dialog} \
--stdout \
--cancel-label "$(eval_gettext 'Exit')" \
--title "$(eval_gettext 'Cpufreq governor configuration')" \
--default-item ${governor} \
--menu \
"\n $(eval_gettext 'please choose a governor (for all CPUs) :')\n\n" \
17 75 3 \
   "powersave" "$(eval_gettext 'Power saving mode, reduces heat')" \
   "performance" "$(eval_gettext 'Run the CPU at the maximum frequency')" )

else

export newgovernor=$(${dialog} \
--stdout \
--cancel-label "$(eval_gettext 'Exit')" \
--title "$(eval_gettext 'Cpufreq governor configuration')" \
--default-item ${governor} \
--menu \
"\n $(eval_gettext 'Current CPU frequency governor set to') \"${governor}\" , $(eval_gettext 'please choose an option (for all CPUs) :')\n\n" \
17 75 5 \
   "powersave" "$(eval_gettext 'Power saving mode, reduces heat')" \
   "ondemand" "$(eval_gettext 'Scales the frequency dynamically')" \
   "conservative" "$(eval_gettext 'Scales the frequency softly')" \
   "performance" "$(eval_gettext 'Run the CPU at the maximum frequency')" )
fi

if [ ! "${newgovernor}" ]; then
	exit 0
else
	sed -i "s/.*SCALING_GOVERNOR=.*/SCALING_GOVERNOR=${newgovernor}/g" /etc/default/cpufreq
	chmod 755 /etc/rc.d/rc.cpufreq
	/bin/bash /etc/rc.d/rc.cpufreq
fi
exit 0


