#!/usr/bin/env bash
# one JSON line every 2s for the quickshell stats panel
hw=$(grep -l coretemp /sys/class/hwmon/hwmon*/name | head -1); hw=${hw%/name}
read -r _ a b c d e f g _ < /proc/stat; prev_idle=$((d+e)); prev_tot=$((a+b+c+d+e+f+g))
while sleep 2; do
    read -r _ a b c d e f g _ < /proc/stat
    idle=$((d+e)); tot=$((a+b+c+d+e+f+g))
    cpu=$(( (100*((tot-prev_tot)-(idle-prev_idle))) / ((tot-prev_tot)>0 ? (tot-prev_tot) : 1) ))
    prev_idle=$idle; prev_tot=$tot
    mt=$(awk '/MemTotal/{print $2}' /proc/meminfo); ma=$(awk '/MemAvailable/{print $2}' /proc/meminfo)
    ctemp=$(( $(cat "$hw/temp1_input" 2>/dev/null || echo 0) / 1000 ))
    IFS=', ' read -r gu gt gmu gmt < <(nvidia-smi --query-gpu=utilization.gpu,temperature.gpu,memory.used,memory.total --format=csv,noheader,nounits 2>/dev/null)
    read -r du dt < <(df -B1G --output=used,size / | tail -1)
    printf '{"cpu":%d,"cpuTemp":%d,"memUsed":%d,"memTotal":%d,"gpu":%d,"gpuTemp":%d,"vramUsed":%d,"vramTotal":%d,"diskUsed":%d,"diskTotal":%d}\n' \
        "$cpu" "$ctemp" $(((mt-ma)/1024)) $((mt/1024)) "${gu:-0}" "${gt:-0}" "${gmu:-0}" "${gmt:-1}" "$du" "$dt"
done
