#!/bin/bash

usage="
        Usage: $(basename "$0") [governor][-h]
      Example: $(basename "$0")
Functionality: It changes the frequency governor for all CPU cores.

      Options:
           -h         Show usage information
"

#if [[ $UID == 0 ]]; then
#	(>&2 echo "DO NOT run with sudo.")
#	echo "$usage"
#	exit 1
#fi

while getopts 'h' OPT; do
    case $OPT in
        h)
            echo "$usage"
			exit 1
    esac
done

if [[ $# -lt 1 ]]; then
  governor="powersave"
else
  governor=$1
fi

# On Ubuntu 22.04, powerprofilesctl controls the power
if [ -x "$(command -v powerprofilesctl)" ]; then
    powerprofilesctl set $1 2>/dev/null 1>/dev/null
fi

numCPU=$(cpufreq-info | grep "analyzing CPU" -c)
maxCPUFreqGHz=$(cpufreq-info | grep "limits:" | grep -Eo "[0-9].[0-9]*\sGHz" | grep -Eo "[0-9].[0-9]*" | head -1)

for i in $(seq 0 1 $((numCPU -1))) ; do
    sudo cpufreq-set --cpu $i -g $governor 1> /dev/null 2>&1
done

# echo "CPU frequency governor has been set to $governor for $numCPU core(s)."