applications/luci-vnstat: rework model, use uci config
[project/luci.git] / applications / luci-vnstat / luasrc / model / cbi / vnstat.lua
1 --[[
2 LuCI - Lua Configuration Interface
3
4 Copyright 2010-2011 Jo-Philipp Wich <xm@subsignal.org>
5
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9
10         http://www.apache.org/licenses/LICENSE-2.0
11 ]]--
12
13 local utl = require "luci.util"
14 local sys = require "luci.sys"
15 local fs  = require "nixio.fs"
16 local nw  = require "luci.model.network"
17
18 local dbdir, line
19
20 for line in io.lines("/etc/vnstat.conf") do
21         dbdir = line:match("^%s*DatabaseDir%s+[\"'](%S-)[\"']")
22         if dbdir then break end
23 end
24
25 dbdir = dbdir or "/var/lib/vnstat"
26
27
28 m = Map("vnstat", translate("VnStat"),
29         translate("VnStat is a network traffic monitor for Linux that keeps a log of network traffic for the selected interface(s)."))
30
31 m.submit = translate("Restart VnStat")
32 m.reset  = false
33
34 nw.init(luci.model.uci.cursor_state())
35
36 local ifaces = { }
37 local enabled = { }
38 local iface
39
40 for iface in fs.dir(dbdir) do
41         if iface:sub(1,1) ~= '.' then
42                 ifaces[iface] = iface
43                 enabled[iface] = iface
44         end
45 end
46
47 for _, iface in ipairs(sys.net.devices()) do
48         ifaces[iface] = iface
49 end
50
51
52 local s = m:section(TypedSection, "vnstat")
53 s.anonymous = true
54 s.addremove = false
55
56 mon_ifaces = s:option(Value, "interface", translate("Monitor selected interfaces"))
57 mon_ifaces.template = "cbi/network_ifacelist"
58 mon_ifaces.widget   = "checkbox"
59 mon_ifaces.cast     = "table"
60
61 function mon_ifaces.write(self, section, val)
62         local i
63         local s = { }
64
65         if val then
66                 for _, i in ipairs(type(val) == "table" and val or { val }) do
67                         s[i] = true
68                 end
69         end
70
71         for i, _ in pairs(ifaces) do
72                 if not s[i] then
73                         fs.unlink(dbdir .. "/" .. i)
74                         fs.unlink(dbdir .. "/." .. i)
75                 end
76         end
77
78         if next(s) then
79                 m.uci:set_list("vnstat", section, "interface", utl.keys(s))
80         else
81                 m.uci:delete("vnstat", section, "interface")
82         end
83 end
84
85 mon_ifaces.remove = mon_ifaces.write
86
87 return m