#!/usr/bin/python3 -I
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2026 Massimo Bollati
"""omemo-sendxmpp: send an OMEMO-encrypted XMPP message (1:1 or group chat), text from stdin.

Arguments compatible with the subset of go-sendxmpp used by dove:
  omemo-sendxmpp [-f conf] [-c] [-a nick] [--suppress-root-warning] [-d state.json] RECIPIENT

conf in go-sendxmpp format (username:, password:, jserver:, port:).
BTBV trust (blind trust before verification). In a group chat it encrypts for
all members/admins/owners (the room must be non-anonymous). If encryption
fails completely it sends in clear (the alert must arrive anyway) and exits 2.
"""
import argparse
import asyncio
import json
import logging
import sys
from pathlib import Path

import oldmemo
from omemo.storage import Just, Nothing, Storage
from slixmpp import JID
from slixmpp.clientxmpp import ClientXMPP
from slixmpp.plugins import register_plugin
from slixmpp_omemo import XEP_0384

log = logging.getLogger("omemo-sendxmpp")


class JsonStorage(Storage):
    def __init__(self, path):
        super().__init__()
        self.path = Path(path)
        try:
            self.data = json.loads(self.path.read_text())
        except Exception:
            self.data = {}

    def _save(self):
        tmp = self.path.with_suffix(".tmp")
        tmp.write_text(json.dumps(self.data))
        tmp.chmod(0o600)
        tmp.replace(self.path)

    async def _load(self, key):
        return Just(self.data[key]) if key in self.data else Nothing()

    async def _store(self, key, value):
        self.data[key] = value
        self._save()

    async def _delete(self, key):
        self.data.pop(key, None)
        self._save()


class Omemo(XEP_0384):
    default_config = {"fallback_message": "OMEMO encrypted message.", "json_file_path": None}

    def plugin_init(self):
        self._st = JsonStorage(self.json_file_path)
        super().plugin_init()

    @property
    def storage(self):
        return self._st

    @property
    def _btbv_enabled(self):
        return True

    async def _devices_blindly_trusted(self, trusted, identifier):
        log.info("BTBV trust: %s", [(d.bare_jid, d.device_id) for d in trusted])

    async def _prompt_manual_trust(self, manually_trusted, identifier):
        pass  # not needed with BTBV; untrusted devices are skipped


register_plugin(Omemo)


def read_conf(path):
    c = {}
    for line in Path(path).read_text().splitlines():
        if ":" in line and not line.lstrip().startswith("#"):
            k, v = line.split(":", 1)
            c[k.strip().lower()] = v.strip()
    return c


class Sender(ClientXMPP):
    def __init__(self, jid, password, to, text, room, nick):
        super().__init__(jid, password)
        self.to, self.text, self.room, self.nick = JID(to), text, room, nick
        self.rc = 1
        self.add_event_handler("session_start", self.start)
        self.add_event_handler("failed_auth", lambda _: self.disconnect())

    async def start(self, _):
        try:
            await self.run()
        except Exception as e:
            log.error("error: %s: %s", type(e).__name__, e)
            self.rc = 1
        await asyncio.sleep(1)
        self.disconnect()

    async def run(self):
        self.send_presence()
        omemo = self.plugin["xep_0384"]
        await omemo.get_session_manager()  # publishes bundle/device list if missing
        mtype = "groupchat" if self.room else "chat"
        rcpts = {JID(self.to.bare)}
        if self.room:
            muc = self.plugin["xep_0045"]
            await muc.join_muc_wait(self.to, self.nick, maxstanzas=0, timeout=20)
            rcpts = set()
            for aff in ("owner", "admin", "member"):
                try:
                    rcpts |= {JID(j) for j in await muc.get_affiliation_list(self.to, aff)}
                except Exception as e:
                    log.warning("cannot read %s list: %s", aff, e)
            for nick in muc.get_roster(self.to):
                j = muc.get_jid_property(self.to, nick, "jid")
                if j:
                    rcpts.add(JID(JID(j).bare))
            rcpts.discard(JID(self.boundjid.bare))
            log.info("OMEMO recipients: %s", sorted(str(j) for j in rcpts))
        msg = self.make_message(mto=self.to, mtype=mtype, mbody=self.text)
        msg.set_from(self.boundjid)
        enc, errors = (None, None)
        try:
            enc, errors = await omemo.encrypt_message(msg, rcpts)
        except Exception as e:
            log.warning("encryption failed: %s: %s", type(e).__name__, e)
        if errors:
            log.warning("non-fatal errors: %s", errors)
        if enc is None:
            log.warning("sending in clear")
            msg.send()
            self.rc = 2
        else:
            enc["eme"]["namespace"] = oldmemo.oldmemo.NAMESPACE
            enc["eme"]["name"] = self.plugin["xep_0380"].mechanisms[oldmemo.oldmemo.NAMESPACE]
            enc.send()
            self.rc = 0
        if self.room:
            self.plugin["xep_0045"].leave_muc(self.to, self.nick)


def main():
    p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    p.add_argument("-f", default="/etc/dove/xmpp.conf")
    p.add_argument("-c", action="store_true", help="recipient is a group chat (MUC)")
    p.add_argument("-a", default="dove", help="nick in the group chat")
    p.add_argument("-d", default="/var/lib/dove/omemo.json", help="OMEMO state (keys, sessions)")
    p.add_argument("-v", action="store_true")
    p.add_argument("--suppress-root-warning", action="store_true")
    p.add_argument("to")
    a = p.parse_args()
    logging.basicConfig(level=logging.INFO if a.v else logging.WARNING, format="%(message)s")
    text = sys.stdin.read().strip()
    if not text:
        sys.exit("empty text")
    c = read_conf(a.f)
    x = Sender(c["username"], c["password"], a.to, text, a.c, a.a)
    for plug in ("xep_0030", "xep_0045", "xep_0060", "xep_0163", "xep_0199", "xep_0380"):
        x.register_plugin(plug)
    x.register_plugin("xep_0384", {"json_file_path": a.d}, module=sys.modules[__name__])
    host = c.get("jserver")
    port = int(c.get("port", 5222))

    x.connect(host, port) if host else x.connect()
    try:
        x.loop.run_until_complete(asyncio.wait_for(x.disconnected, 60))
    except asyncio.TimeoutError:
        log.error("timeout")
        x.rc = 1
    sys.exit(x.rc)


if __name__ == "__main__":
    main()
