64 lines
2.1 KiB
Python
64 lines
2.1 KiB
Python
#!/usr/bin/python3
|
|
"""Add the managed include to the HTTPS server while preserving other edits."""
|
|
import os
|
|
import re
|
|
import sys
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
config = Path("/etc/nginx/sites-available/raymand-cti")
|
|
includes = (
|
|
" include /etc/nginx/raymand-cti/webrtc.conf;\n",
|
|
)
|
|
|
|
try:
|
|
original_text = config.read_text(encoding="utf-8")
|
|
# Remove obsolete includes before calculating the HTTPS block's closing index.
|
|
lines = [line for line in original_text.splitlines(keepends=True)
|
|
if "/etc/nginx/raymand-cti/custom-proxies.conf" not in line]
|
|
start = None
|
|
depth = 0
|
|
has_tls = False
|
|
insert_at = None
|
|
for index, line in enumerate(lines):
|
|
stripped = line.strip()
|
|
if start is None:
|
|
if re.match(r"server\s*\{", stripped):
|
|
start = index
|
|
depth = line.count("{") - line.count("}")
|
|
has_tls = False
|
|
continue
|
|
if stripped.startswith("#"):
|
|
continue
|
|
if re.search(r"\blisten\s+(?:\[::\]:)?\d+\s+ssl\b", stripped):
|
|
has_tls = True
|
|
depth += line.count("{") - line.count("}")
|
|
if depth == 0:
|
|
if has_tls:
|
|
insert_at = index
|
|
break
|
|
start = None
|
|
if insert_at is None:
|
|
raise RuntimeError("Could not find the Raymand CTI HTTPS server block")
|
|
existing_text = "".join(lines)
|
|
missing = [include for include in includes if include.strip() not in existing_text]
|
|
if not missing and existing_text == original_text:
|
|
raise SystemExit(0)
|
|
lines[insert_at:insert_at] = missing
|
|
fd, temp_name = tempfile.mkstemp(prefix=".raymand-cti.", dir=str(config.parent))
|
|
try:
|
|
os.fchmod(fd, 0o644)
|
|
with os.fdopen(fd, "w", encoding="utf-8") as stream:
|
|
stream.writelines(lines)
|
|
stream.flush()
|
|
os.fsync(stream.fileno())
|
|
os.replace(temp_name, config)
|
|
finally:
|
|
try:
|
|
os.unlink(temp_name)
|
|
except FileNotFoundError:
|
|
pass
|
|
except Exception as error:
|
|
print(str(error), file=sys.stderr)
|
|
sys.exit(1)
|