#!/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
# Ported to yad (X-only, no gettext) by Claude.

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

if ! command -v yad >/dev/null 2>&1; then
  echo "yad is required but was not found in PATH." >&2
  exit 1
fi

if [ ! "$DISPLAY" ]; then
  echo "This program requires a running X session." >&2
  exit 1
fi

export PATH="${PATH}:/usr/sbin:/sbin"

if [ "$(id -u)" != "0" ]; then
  yad --center --title "Root only" --text "You need to be root to run $(basename $0)" --button="OK:0"
  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
  newgovernor=$(yad --center --width=460 --height=160 \
    --title "Cpufreq governor configuration" \
    --text "<b>Current governor:</b> $governor\nPlease choose a governor (for all CPUs):" \
    --list --no-headers \
    --column="Governor" --column="Description" \
    --button="Exit:1" --button="Select:0" \
    --print-column=1 \
    "powersave" "Power saving mode, reduces heat" \
    "performance" "Run the CPU at the maximum frequency")
else
  newgovernor=$(yad --center --width=460 --height=320 \
    --title "Cpufreq governor configuration" \
    --text "<b>Current governor:</b> $governor\nPlease choose an option (for all CPUs):" \
    --list --no-headers \
    --column="Governor" --column="Description" \
    --button="Exit:1" --button="Select:0" \
    --print-column=1 \
    "powersave" "Power saving mode, reduces heat" \
    "ondemand" "Scales the frequency dynamically" \
    "conservative" "Scales the frequency softly" \
    "performance" "Run the CPU at the maximum frequency")
fi
rc=$?
newgovernor="${newgovernor%|}"

if [ $rc -ne 0 ] || [ ! "${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
