#!/usr/bin/env bash
#
# Read temperature status in Linux
set -euo pipefail
IFS=$'\n\t'
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

SLEEP_INTERVAL=${SLEEP_INTERVAL:-30}

function print_all_x86_pkg_temps {
    for thermal_zone in /sys/class/thermal/thermal_zone*; do
        local thermal_zone_type=$(cat "$thermal_zone/type")
        if [ "$thermal_zone_type" != "x86_pkg_temp" ] && [ "$thermal_zone_type" != "acpitz" ]; then
            continue
        fi
        local thermal_zone_temperature=$(cat "$thermal_zone/temp")
        echo "$thermal_zone_temperature"
    done
}

while true; do
    sum_temperature=0
    num_temperature=0
    max_temperature=0
    while read temp; do
        numeric_temp=$(bc -s <<<"$temp / 1000.0")
        sum_temperature=$(bc -s <<<"$sum_temperature + $numeric_temp")
        num_temperature=$((num_temperature + 1))
        max_temperature=$(bc <<EOF
define max(a,b){
  if(a>b)
  {
   return(a)
  }else{
   return(b)
  }
}
max($max_temperature,$numeric_temp)
EOF
                       )
    done<<<$(print_all_x86_pkg_temps)
    avg_temperature=$(bc -s <<<"$sum_temperature / $num_temperature")
    tooltip=""
    class=""
    icon="🌡"

    jq --unbuffered --compact-output <<EOF
{
"text":"${max_temperature}℃ ${icon}",
"tooltip":"${tooltip//$'\n'/\\n}",
"percentage":50,
"class":"${class}"
}
EOF
    sleep $SLEEP_INTERVAL
done
