Create, update and remove wmii bar boxes.

#!/usr/bin/env lua

-- Create, update and remove wmii bar boxes.
--
-- Copyright (c) 2009 Jochen Kupperschmidt <http://homework.nwsnet.de/>
-- Version: 14-Aug-2009
-- Released under the terms of the MIT License.

-- configuration
local LOCALE = "de_DE.UTF-8"

-- Update the content of the named bar field.
function update_bar_field(name, value)
    local f = io.popen("wmiir write /rbar/" .. name, "w")
    f:write(value)
    f:close()
end

-- Get the load average.
function get_loadavg()
    -- Read the first (and only) line of uptime's output.
    local f = io.popen("uptime")
    local line = f:read("*l")
    f:close()

    -- Extract and format the load average.
    local match = line:match("load average: (.*)$")
    if match ~= nil then
        local replaced, count = match:gsub(",", "", 2)
        return replaced
    end
    return nil
end

-- bar fields
local bar_fields = {
    ["01_load"] = function()
        return get_loadavg()
    end,
    ["02_date"] = function()
        return os.date("%A, %d. %B %Y")
    end,
    ["03_time"] = function()
        return os.date("%H:%M:%S") .. " Uhr"
    end,
}

-- commands
local cmds = {
    {"create", "Create bar fields.", function()
        for bar_field_name, func in pairs(bar_fields) do
            local f = io.popen("wmiir create /rbar/" .. bar_field_name, "w")
            f:write("")
            f:close()
        end
    end},

    {"update", "Update bar fields.", function()
        os.setlocale(LOCALE)
        for bar_field_name, func in pairs(bar_fields) do
            update_bar_field(bar_field_name, func())
        end
    end},

    {"remove", "Remove bar fields.", function()
        for bar_field_name, func in pairs(bar_fields) do
            os.execute("wmiir remove /rbar/" .. bar_field_name)
        end
    end},
}
table.insert(cmds, 1,
    {"help", "List available commands.", function()
        for i, cmd in pairs(cmds) do
            io.write(string.format("  %-8s\t%s\n", cmd[1], cmd[2]))
        end
    end})

for i, cmd in ipairs(cmds) do
    if cmd[1] == arg[1] then
        cmd[3]()
        os.exit(0)
    end
end
print("Unknown command. See '" .. arg[0]
    .. " help' for available commands.")
os.exit(2)