#!/usr/bin/env bash
# CPU%, RAM%, Disk% (root), Temp(°C) as JSON for eww.

# --- CPU (delta over a short sample) ---
read -r _ a b c d _ < /proc/stat; t1=$((a+b+c+d)); idle1=$d
sleep 0.3
read -r _ a b c d _ < /proc/stat; t2=$((a+b+c+d)); idle2=$d
dt=$((t2 - t1)); di=$((idle2 - idle1))
cpu=0; [ "$dt" -gt 0 ] && cpu=$(( (100 * (dt - di)) / dt ))

# --- RAM ---
mt=$(awk '/MemTotal/{print $2}' /proc/meminfo)
ma=$(awk '/MemAvailable/{print $2}' /proc/meminfo)
mem=0; [ "${mt:-0}" -gt 0 ] && mem=$(( (100 * (mt - ma)) / mt ))

# --- Disk (root) ---
disk=$(df -P / | awk 'NR==2{gsub("%","",$5); print $5}')

# --- Temp (sensors → fallback thermal zone) ---
temp=$(sensors -j 2>/dev/null | jq -r '
  [.. | objects | to_entries[] | select(.key|test("temp.*_input")) | .value]
  | map(select(. > 0)) | if length > 0 then (add/length) else 0 end' 2>/dev/null)
if [ -z "$temp" ] || [ "$temp" = "null" ] || [ "$temp" = "0" ]; then
  temp=$(awk '{printf "%d", $1/1000}' /sys/class/thermal/thermal_zone0/temp 2>/dev/null)
fi
temp=$(printf '%.0f' "${temp:-0}")

jq -nc --argjson cpu "${cpu:-0}" --argjson mem "${mem:-0}" \
       --argjson disk "${disk:-0}" --argjson temp "${temp:-0}" \
  '{cpu:$cpu,mem:$mem,disk:$disk,temp:$temp}'
