#!/usr/bin/env python3
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
"""The Edge Agent's start as a Home Assistant add-on (runs as root).

- Home Assistant's instance id: .storage/core.uuid is root-only; a copy in
  /data for the link (the site id comes from it, as on the Hub and THR-Home).
- The add-on's options (/data/options.json): mode, claim code, dashboards.
- MQTT: the broker the Supervisor offers (the Mosquitto add-on), with the
  login it made for this add-on; without one, no discovery in HA.
- First start: config.yaml and an empty mapping, as the Hub's edge-prepare
  (nothing is sent until an installer confirms the mapping).
Then the link and the agent (cantabile-run) as uid 10001, without root's
capabilities: /homeassistant stays mapped, but only what is readable for
everyone is readable for them.
ADDON_DATA, ADDON_HA_CONFIG, ADDON_ETC, SUPERVISOR_URL and ADDON_DRY_RUN=1
(print the environment instead of starting) are for tests.
"""
import json
import os
import pwd
import sys
import urllib.request

DATA = os.environ.get("ADDON_DATA", "/data")
HA_CONFIG = os.environ.get("ADDON_HA_CONFIG", "/homeassistant")
ETC = os.environ.get("ADDON_ETC", "/etc/cantabile")
SUPERVISOR = os.environ.get("SUPERVISOR_URL", "http://supervisor")
DRY = os.environ.get("ADDON_DRY_RUN") == "1"
USER = "cantabile"   # edge/Dockerfile: uid 10001

CONFIG = """# The Edge Agent as a Home Assistant add-on (written once by addon-run).
mode: shadow
mapping: /data/mapping.yaml
state_dir: /data/state
sink: {kind: link, path: /run/cantabile/link.sock}
"""
MAPPING = """# Which HA entities Cantabile may read (edge/cantabile_edge/mapping.py).
# None yet: an installer confirms the mapping.
version: 1
assets: []
"""


def log(msg):
    print(f"addon-run: {msg}", flush=True)


def owner():
    if DRY or os.geteuid() != 0:
        return None
    pw = pwd.getpwnam(USER)
    return pw.pw_uid, pw.pw_gid


def put(path, text, mode=0o600, own=None, keep=False):
    """Write a file the agent's user owns; keep=True: only if missing."""
    if keep and os.path.exists(path):
        return
    os.makedirs(os.path.dirname(path), exist_ok=True)
    tmp = path + ".tmp"
    with open(tmp, "w") as f:
        f.write(text)
    os.chmod(tmp, mode)
    if own:
        os.chown(tmp, *own)
    os.replace(tmp, path)


def chown_tree(path, own):
    """The agent's files in /data (options.json stays the Supervisor's)."""
    for root, dirs, files in os.walk(path):
        for n in dirs + files:
            p = os.path.join(root, n)
            if p != os.path.join(DATA, "options.json") and not os.path.islink(p):
                os.chown(p, *own)
    os.chown(path, *own)


def mqtt(env, own):
    token = os.environ.get("SUPERVISOR_TOKEN", "")
    req = urllib.request.Request(f"{SUPERVISOR}/services/mqtt", headers={"Authorization": f"Bearer {token}"})
    try:
        with urllib.request.urlopen(req, timeout=10) as r:
            d = json.load(r)["data"]
    except Exception as e:   # no broker add-on: the agent runs without HA discovery
        log(f"no MQTT broker from the Supervisor ({e}): no Cantabile device in Home Assistant")
        return
    if d.get("ssl"):
        log("the MQTT broker wants TLS, which the agent does not speak yet: no Cantabile device in Home Assistant")
        return
    env["CANTABILE_MQTT_HOST"] = str(d["host"])
    env["CANTABILE_MQTT_PORT"] = str(d.get("port", 1883))
    if d.get("username"):
        env["CANTABILE_MQTT_USER"] = d["username"]
        put(f"{DATA}/mqtt-password", d.get("password", ""), own=own)
        env["CANTABILE_MQTT_PASSWORD_FILE"] = f"{DATA}/mqtt-password"
    log(f"MQTT broker {d['host']}:{env['CANTABILE_MQTT_PORT']}")


def main():
    own = owner()
    with open(f"{DATA}/options.json") as f:
        opts = json.load(f)
    env = dict(os.environ)
    # The platform this build belongs to (ha-addon/build.sh: addon.env).
    with open(f"{ETC}/addon.env") as f:
        for line in f:
            k, sep, v = line.strip().partition("=")
            if sep and not k.startswith("#"):
                env.setdefault(k, v)
    env["CANTABILE_COMMAND_CERT"] = f"{ETC}/commands.pem"
    if os.path.exists(f"{ETC}/bundles.pem"):
        env["CANTABILE_BUNDLE_CERT"] = f"{ETC}/bundles.pem"

    with open(f"{HA_CONFIG}/.storage/core.uuid") as f:
        put(f"{DATA}/ha-core.uuid", f.read(), own=own)
    env["CANTABILE_HA_UUID_FILE"] = f"{DATA}/ha-core.uuid"

    code = (opts.get("claim_code") or "").strip()
    if code:
        put(f"{DATA}/claim-code", code + "\n", own=own)
    env["CANTABILE_MODE"] = opts.get("mode", "shadow")
    env["CANTABILE_DASHBOARDS"] = "1" if opts.get("dashboards", True) else "0"
    mqtt(env, own)

    put(f"{DATA}/config.yaml", CONFIG, 0o644, own, keep=True)
    put(f"{DATA}/mapping.yaml", MAPPING, 0o644, own, keep=True)
    os.makedirs(f"{DATA}/state", exist_ok=True)
    if own:
        chown_tree(DATA, own)

    cmd = ["cantabile-run", "--config", f"{DATA}/config.yaml", "run"]
    if DRY:
        print(json.dumps({"cmd": cmd, "env": {k: v for k, v in env.items() if k.startswith(("CANTABILE_", "HA_"))}}))
        return
    if own:
        # Drop to the agent's user and every capability; no way back.
        cmd = ["setpriv", f"--reuid={own[0]}", f"--regid={own[1]}", "--init-groups",
               "--inh-caps=-all", "--bounding-set=-all", "--no-new-privs"] + cmd
    os.execvpe(cmd[0], cmd, env)


if __name__ == "__main__":
    try:
        main()
    except FileNotFoundError as e:
        log(f"missing {e.filename}")
        sys.exit(1)
