-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathconf.py
More file actions
97 lines (79 loc) · 3.02 KB
/
Copy pathconf.py
File metadata and controls
97 lines (79 loc) · 3.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# Copyright (c) 2008-2019 Alon Swartz <alon@turnkeylinux.org>
# - all rights reserved
# Copyright (c) 2020 TurnKey GNU/Linux <admin@turnkeylinux.org>
# - all rights reserved
import os
class ConfconsoleConfError(Exception):
pass
def path(filename: str) -> str:
for dir in ("conf", "/etc/confconsole"):
path = os.path.join(dir, filename)
if os.path.exists(path):
return path
raise ConfconsoleConfError(
f"could not find configuration file: {filename}"
)
class Conf:
default_nic: str | None
publicip_cmd: str | None
networking: bool
copy_paste: bool
conf_file: str
def _load_conf(self) -> None:
if not self.conf_file or not os.path.exists(self.conf_file):
return
with open(self.conf_file) as fob:
for line in fob:
line = line.strip()
if not line or line.startswith("#"):
continue
parts = line.split(maxsplit=1)
op = parts[0]
val = parts[1] if len(parts) > 1 else ""
if op == "default_nic":
self.default_nic = val
elif op == "publicip_cmd":
self.publicip_cmd = val
elif op == "networking" and val in ("true", "false"):
self.networking = True if val == "true" else False
elif op == "autostart":
pass
elif op == "copy_paste" and val.lower() in ("true", "false"):
self.copy_paste = True if val.lower() == "true" else False
else:
raise ConfconsoleConfError(
f"illegal configuration line: {line}"
)
def __init__(self) -> None:
self.default_nic = None
self.publicip_cmd = None
self.networking = True
self.copy_paste = True
self.conf_file = path("confconsole.conf")
self._load_conf()
def set_default_nic(self, ifname: str) -> None:
self.default_nic = ifname
new_line = f"default_nic {ifname}\n"
lines: list[str] = []
replaced = False
if os.path.exists(self.conf_file):
with open(self.conf_file) as fob:
for line in fob:
stripped = line.strip()
if (
stripped
and not stripped.startswith("#")
and stripped.split()[0] == "default_nic"
):
# update existing setting in place
lines.append(new_line)
replaced = True
else:
# preserve comments, blank lines and other settings
lines.append(line)
if not replaced:
if lines and not lines[-1].endswith("\n"):
lines[-1] += "\n"
lines.append(new_line)
with open(self.conf_file, "w") as fob:
fob.writelines(lines)