local memory = {}

local DEFAULT_SIGNAL = "memory::value"

local mem = [[
  while IFS=':k ' read -r mem1 mem2 _; do
    case "$mem1" in
      MemTotal)
        memt="$(( mem2 / 1024 ))";;
      MemAvailable)
        memu="$(( memt - mem2 / 1024))";;
    esac;
  done < /proc/meminfo;
  printf "%d %d" "$memu" "$memt"; ]]

--- callback: function(total, available)
function memory.get(callback)
	awful.spawn.easy_async_with_shell(mem, function (out)
		local val = gears.string.split(out, " ")
		callback(tonumber(val[1]), tonumber(val[2]))
	end)
end

function memory.emit(name)
	memory.get(function(...)
		awesome.emit_signal(name or DEFAULT_SIGNAL, ...)
	end)
end

function memory.register_signal(signal_name, update_interval)
	gears.timer {
		timeout = update_interval or 5,
		call_now = true,
		autostart = true,
		callback = function() memory.emit(signal_name) end
	}
end

return memory
