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