-- Read the tiny kernel meminfo pseudo-file every five seconds.  This avoids a
-- resident helper process and reuses Noctalia's lightweight widget lifecycle.
local command = [[awk '
$1 == "MemTotal:" { total = $2 }
$1 == "MemAvailable:" { available = $2 }
$1 == "SwapTotal:" { swap_total = $2 }
$1 == "SwapFree:" { swap_free = $2 }
END {
  if (!total || !available) exit 1
  used = total - available
  if (swap_total > 0) {
    swap_used = (swap_total - swap_free) * 100 / swap_total
    printf "RAM %.1f/%.1f GiB  S %.0f%%\n", used / 1048576, total / 1048576, swap_used
  } else {
    printf "RAM %.1f/%.1f GiB  S —\n", used / 1048576, total / 1048576
  }
}' /proc/meminfo]]

local request_in_flight = false

function update()
  noctalia.setUpdateInterval(5000)

  if request_in_flight then
    return
  end

  request_in_flight = true
  noctalia.runAsync(command, function(result)
    request_in_flight = false

    if result.exitCode ~= 0 then
      barWidget.setText("RAM —")
      barWidget.setTooltip("Unable to read /proc/meminfo")
      return
    end

    local text = string.gsub(result.stdout, "%s+$", "")
    barWidget.setGlyph("memory")
    barWidget.setText(text)
    barWidget.setTooltip("RAM used / total · S = swap used")
  end)
end
