#!/bin/bash

# omarchy:summary=Print CPU and memory stats for the shell
# omarchy:group=system
# omarchy:args=[--bar-widget]

bar_widget_stats() {
  LC_ALL=C awk '
    FILENAME == "/proc/stat" && FNR == 1 {
      idle = $5
      total = 0
      for (i = 2; i <= NF; i++) total += $i
      printf "cpu\t%s\t%s\n", idle, total
      nextfile
    }
    FILENAME == "/proc/meminfo" {
      if ($1 == "MemTotal:") mem_total = $2
      else if ($1 == "MemAvailable:") mem_avail = $2
    }
    FILENAME == "/proc/loadavg" {
      load = $1
      nextfile
    }
    END {
      if (mem_total > 0) printf "memory\t%.2f\n", ((mem_total - mem_avail) / mem_total) * 100
      if (load != "") print "load\t" load
    }
  ' /proc/stat /proc/meminfo /proc/loadavg
}

case "${1:-}" in
  "")
    ;;
  --bar-widget)
    bar_widget_stats
    exit
    ;;
  *)
    echo "Usage: omarchy-system-stats [--bar-widget]" >&2
    exit 1
    ;;
esac

# The C locale keeps top's labels English and its commas mere separators, never "84,3" decimals.
# Commas become spaces because at full idle top writes "ni,100.0 id" with none.
cpu=$(LC_ALL=C top -bn1 | awk '/^%?Cpu/ {
  gsub(/,/, " ")
  for (i = 1; i <= NF; i++) {
    if ($(i + 1) == "id") {
      printf "%.0f%%", 100 - $i
      exit
    }
  }
}')

awk -v cpu="$cpu" '
  /^MemTotal:/ { total = $2 }
  /^MemAvailable:/ { avail = $2 }
  END {
    used = total - avail
    printf "cpu\t%s\n", cpu
    printf "memory\t%.1fGB / %.0fGB\n", used / 1024 / 1024, total / 1024 / 1024
  }
' /proc/meminfo
