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

SLEEP_INTERVAL=${SLEEP_INTERVAL:-30}

while true; do
    current_cpu_temps=$(sysctl 'hw.acpi.thermal' | grep -E 'hw\.acpi\.thermal\.tz[0-9]+\.temperature' | sort)
    #current_cpu_temps=$(sysctl 'dev.cpu' | grep -E 'dev\.cpu\.[0-9]+\.temperature' | sort)
    sum_temperature=0
    num_temperature=0
    max_temperature=0
    while read temp; do
        numeric_temp=$(echo "$temp" | cut -d ':' -f 2 | grep -oE '[0-9]+(\.[0-9]+)?')
        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<<<"$current_cpu_temps"
    avg_temperature=$(bc -s <<<"$sum_temperature / $num_temperature")
    tooltip="<tt>$current_cpu_temps</tt>"
    class=""
    icon="🌡"

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