Rework LuCI build system
[project/luci.git] / applications / luci-app-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 if fs.access(dbdir) then
41         for iface in fs.dir(dbdir) do
42                 if iface:sub(1,1) ~= '.' then
43                         ifaces[iface] = iface
44                         enabled[iface] = iface
45                 end
46         end
47 end
48
49 for _, iface in ipairs(sys.net.devices()) do
50         ifaces[iface] = iface
51 end
52
53
54 local s = m:section(TypedSection, "vnstat")
55 s.anonymous = true
56 s.addremove = false
57
58 mon_ifaces = s:option(Value, "interface", translate("Monitor selected interfaces"))
59 mon_ifaces.template   = "cbi/network_ifacelist"
60 mon_ifaces.widget     = "checkbox"
61 mon_ifaces.cast       = "table"
62 mon_ifaces.noinactive = true
63 mon_ifaces.nocreate   = true
64
65 function mon_ifaces.write(self, section, val)
66         local i
67         local s = { }
68
69         if val then
70                 for _, i in ipairs(type(val) == "table" and val or { val }) do
71                         s[i] = true
72                 end
73         end
74
75         for i, _ in pairs(ifaces) do
76                 if not s[i] then
77                         fs.unlink(dbdir .. "/" .. i)
78                         fs.unlink(dbdir .. "/." .. i)
79                 end
80         end
81
82         if next(s) then
83                 m.uci:set_list("vnstat", section, "interface", utl.keys(s))
84         else
85                 m.uci:delete("vnstat", section, "interface")
86         end
87 end
88
89 mon_ifaces.remove = mon_ifaces.write
90
91 return m