#!/usr/bin/env bash
# RAM and swap from /proc/meminfo every 3 s.  "used" follows `free`
# (total - available); "cached" is buffers + page cache + reclaimable slab.
# Human values use SI units like the previous `free --si`.
while :; do
  awk '
    /^MemTotal:/     { t = $2 }   /^MemAvailable:/ { a = $2 }
    /^Buffers:/      { b = $2 }   /^Cached:/       { c = $2 }
    /^SReclaimable:/ { s = $2 }   /^SwapTotal:/    { st = $2 }
    /^SwapFree:/     { sf = $2 }
    function h(kb) { return kb >= 1000000 ? sprintf("%.1fG", kb / 1000000) : sprintf("%.0fM", kb / 1000) }
    END {
      used = t - a; cached = b + c + s; su = st - sf
      printf "{\"total\":%d,\"used\":%d,\"cached\":%d,\"human\":{\"total\":\"%s\",\"used\":\"%s\",\"cached\":\"%s\"},", t, used, cached, h(t), h(used), h(cached)
      printf "\"swap\":{\"total\":%d,\"used\":%d,\"human\":{\"total\":\"%s\",\"used\":\"%s\"}}}\n", st, su, h(st), h(su)
    }' /proc/meminfo
  sleep 3
done
