#!/usr/bin/env bash

THERMAL_PATH="/sys/devices/virtual/thermal"

# Build a numerically (version) sorted list of zone names (basenames).
get_zones() {
  shopt -s nullglob
  mapfile -t ZONES < <(
    printf "%s\n" "$THERMAL_PATH"/thermal_zone* \
    | xargs -n1 basename \
    | LC_ALL=C sort -V
  )
}

get_zones

echo "Monitoring thermal zones... (Ctrl+C to stop)"
sleep 0.2

while :; do
  clear
  printf "%-14s %-18s %-12s %-6s\n" "Zone" "Type" "cdev" "Temp (°C)"
  echo "--------------------------------------------------------------"

  for zn in "${ZONES[@]}"; do
    zpath="$THERMAL_PATH/$zn"
    tfile="$zpath/temp"
    yfile="$zpath/type"
    cfile="$zpath/cdev0/type"

    # Type
    if [[ -r "$yfile" ]]; then
      type=$(<"$yfile")
    else
      type="unknown"
    fi

    # cdev
    if [[ -r "$cfile" ]]; then
      cdev=$(<"$cfile")
    else
      cdev="unknown"
    fi

    # Temp (scale millidegrees to °C, show one decimal if needed)
    if [[ -r "$tfile" ]]; then
      raw=$(<"$tfile")
      # keep only leading digits in case of odd contents
      raw=${raw%%[!0-9]*}
      if [[ -n "$raw" ]]; then
        if (( raw >= 1000 )); then
          temp=$(awk -v v="$raw" 'BEGIN{printf "%.1f", v/1000}')
        else
          temp="$raw"
        fi
      else
        temp="N/A"
      fi
    else
      temp="N/A"
    fi

    printf "%-14s %-18s %-12s %-6s\n" "$zn" "$type" "$cdev" "$temp"
  done

  # Uncomment the next line if zones can appear/disappear and you want to rescan each tick:
  # get_zones

  sleep 1
done
