#! /bin/bash
# Usage:       cpu-temp-speed
#
# Monitors CPU clock speed and temperature.
# 
# 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 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
for file in /usr/lib/bash/sleep /usr/lib32/bash/sleep /usr/lib64/bash/sleep; do [ -r "$file" ] && enable -f "$file" sleep && break; done

policies=(/sys/devices/system/cpu/cpufreq/policy[0-9]*)
temps=(/sys/class/thermal/thermal_zone?/temp)
temptypes=(/sys/class/thermal/thermal_zone?/type)

[ ! -e "${policies[0]}" ] && echo "No CPUs found!" && exit
[ ! -e "${temps[0]}" ] && echo "No temperatures found!" && exit

# CPU core count header
policycount=${#policies[@]}
echo -n "["
c=","
for i in ${!policies[@]}; do
	read -a policycores < ${policies[$i]}/affected_cpus
	cores=${#policycores[@]}
	[[ ! $cores -eq 1 ]] && s="s" || s=""
	[[ $policycount -eq $((i+1)) ]] && c=" "
	printf " %1.0f core%0s$c" $cores $s
done
echo -n "] "

# Temperature header
typecount=${#temptypes[@]}
echo -n "["
c=","
for i in ${!temptypes[@]}; do
	read -a temptype < ${temptypes[$i]}
	[[ $typecount -eq $((i+1)) ]] && c=""
	printf " %4s$c" ${temptype%"-thermal"}
done
echo " ]"

while true; do
	block1=""
	block2=""
	for cf in ${policies[@]}; do
		read clk < $cf/scaling_cur_freq
		printf -v tmp "%4.0fMHz " $((clk))e-3
		block1+="$tmp"
	done
	for ct in ${temps[@]}; do
		read cpu < $ct
		printf -v tmp "%3.0f°C " $((cpu))e-3
		block2+="$tmp"
	done
	echo -ne "\r[ $block1] [ $block2]"
	sleep 0.5
done
