]> www.average.org Git - loctrkd.git/blob - gps303/common.py
6e4a2f36209f05a37198a0735c4a8cd0a323c3cd
[loctrkd.git] / gps303 / common.py
1 """ Common housekeeping for all daemons """
2
3 from configparser import ConfigParser
4 from getopt import getopt
5 from logging import getLogger, StreamHandler, DEBUG, INFO
6 from sys import argv, stderr, stdout
7
8 CONF = "/etc/gps303.conf"
9 PORT = 4303
10 DBFN = "/var/lib/gps303/gps303.sqlite"
11
12
13 def init(log, opts=None):
14     if opts is None:
15         opts, _ = getopt(argv[1:], "c:d")
16     opts = dict(opts)
17     conf = readconfig(opts["-c"] if "-c" in opts else CONF)
18     if stdout.isatty():
19         log.addHandler(StreamHandler(stderr))
20     else:
21         log.addHandler(SysLogHandler(address="/dev/log"))
22     log.setLevel(DEBUG if "-d" in opts else INFO)
23     log.info("starting with options: %s", opts)
24     return conf
25
26
27 def readconfig(fname):
28     config = ConfigParser()
29     config["collector"] = {
30         "port": PORT,
31     }
32     config["storage"] = {
33         "dbfn": DBFN,
34     }
35     config["termconfig"] = {}
36     config.read(fname)
37     return config
38
39
40 def normconf(section):
41     result = {}
42     for key, val in section.items():
43         vals = val.split("\n")
44         if len(vals) > 1 and vals[0] == "":
45             vals = vals[1:]
46         lst = []
47         for el in vals:
48             try:
49                 el = int(el, 0)
50             except ValueError:
51                 if el[0] == '"' and el[-1] == '"':
52                     el = el.strip('"').rstrip('"')
53             lst.append(el)
54         if len(lst) == 1:
55             [lst] = lst
56         result[key] = lst
57     return result
58
59
60 if __name__ == "__main__":
61     from sys import argv
62
63     def _print_config(conf):
64         for section in conf.sections():
65             print("section", section)
66             for option in conf.options(section):
67                 print("    ", option, conf[section][option])
68
69     conf = readconfig(argv[1])
70     _print_config(conf)
71     print(normconf(conf["termconfig"]))