"""Finish this session's owned tools only; no Contextra state mutation."""
import json
import os
from pathlib import Path
import shutil

assert os.geteuid()==0
stage=Path("/home/si/.local/share/contextra-offline-prep/20260928-r01/maintenance")
prefix=Path("/usr/local/lib/contextra-maintenance/20260928-r01")
assert prefix.is_dir() and not prefix.is_symlink()
for path in stage.glob("*.py"):
    if path.name.startswith("test_"):
        continue
    target=prefix/path.name
    if target.is_symlink():
        raise RuntimeError("Target symlink")
    shutil.copyfile(path,target)
    target.chmod(0o644)
vendor=stage/"bridge_tools"
if vendor.is_dir():
    shutil.copytree(vendor,prefix/"bridge_tools",dirs_exist_ok=True,ignore=shutil.ignore_patterns("__pycache__"))
    for p in (prefix/"bridge_tools").rglob("*"):
        if p.is_symlink():raise RuntimeError("Vendor symlink")
        p.chmod(0o755 if p.is_dir() else 0o644)
unit=Path("/etc/systemd/system/contextra-runtime.service")
line="ExecStartPre=/usr/bin/python3 /usr/local/lib/contextra-maintenance/20260928-r01/maintenance_guard.py\n"
text=unit.read_text()
if line not in text:
    assert text.count("[Service]\n")==1
    saved=Path("/var/lib/contextra-maintenance/service-before-guard")
    if saved.exists():raise RuntimeError("Existing guard journal requires review")
    saved.write_text(text)
    saved.chmod(0o600)
    unit.write_text(text.replace("[Service]\n","[Service]\n"+line))
conf=Path("/etc/contextra-maintenance/observability/compose.json")
doc=json.loads(conf.read_text())
doc["services"]["grafana"]["environment"].update({"GF_PLUGINS_PREINSTALL_DISABLED":"true","GF_PLUGINS_PREINSTALL_AUTO_UPDATE":"false"})
conf.write_text(json.dumps(doc,indent=2))
print("Owned tool update complete; Grafana automatic plugin installs/updates disabled persistently")
