#!/usr/bin/env python3
"""
Ring2All NMS Native Node Control Agent (r2a-node-agent)
Zero-dependency Python 3 stdlib HTTPS control API listening on TCP 9443.
Authenticated exclusively via constant-time X-NMS-Node-Token (256-bit random
per-node secret stored in /etc/softswitch/nms-agent.env, mode 0600) and
restricted at the kernel nftables layer to the Ring2All NMS server IP.
"""
import hmac
import http.server
import json
import os
import re
import socket
import ssl
import subprocess
import time
from pathlib import Path

BIND_HOST = os.environ.get("NMS_AGENT_BIND", "0.0.0.0")
BIND_PORT = int(os.environ.get("NMS_AGENT_PORT", "9443"))
NODE_ROLE = os.environ.get("NODE_ROLE", "unknown").strip()
NODE_TOKEN = os.environ.get("NMS_NODE_TOKEN", "").strip()
TLS_CERT = os.environ.get("NMS_AGENT_CERT", "/etc/softswitch/nms-agent.crt")
TLS_KEY = os.environ.get("NMS_AGENT_KEY", "/etc/softswitch/nms-agent.key")

ALLOWED_SERVICES_BY_ROLE = {
    "pg_ha": {"patroni", "etcd", "snmpd", "nftables", "r2a-node-agent"},
    "storage_gluster": {"glusterd", "snmpd", "nftables", "r2a-node-agent"},
    "pbx_admin": {"softswitch-api", "softswitch-monitoring-api", "haproxy", "nginx", "snmpd", "nftables", "r2a-node-agent"},
    "pbx_telephony": {"freeswitch", "haproxy", "snmpd", "nftables", "r2a-node-agent"},
    "sbc_edge": {"kamailio", "rtpengine", "sbc-api", "haproxy", "nginx", "snmpd", "nftables", "r2a-node-agent"},
    "sbc_media": {"ngcp-rtpengine-daemon", "snmpd", "nftables", "r2a-node-agent"},
    "video_sfu": {"softswitch-video-sfu", "softswitch-video-sip", "softswitch-video-egress", "redis-server", "snmpd", "nftables", "r2a-node-agent"},
    "bss_admin": {"softswitch-bss-api", "haproxy", "nginx", "snmpd", "nftables", "r2a-node-agent"},
    "bss_client": {"nginx", "snmpd", "nftables", "r2a-node-agent"},
}
DEFAULT_SERVICES = {"snmpd", "nftables", "r2a-node-agent", "nginx", "haproxy"}
SAFE_IP_RE = re.compile(r"^\d{1,3}(?:\.\d{1,3}){3}(?:/\d{1,2})?$")
SAFE_TZ_RE = re.compile(r"^[A-Za-z0-9_/+.-]{1,64}$")


def run_cmd(args, timeout=20):
    try:
        proc = subprocess.run(
            args,
            capture_output=True,
            text=True,
            timeout=timeout,
            shell=False,
        )
        return proc.returncode, proc.stdout.strip(), proc.stderr.strip()
    except Exception as exc:
        return 1, "", str(exc)


def collect_role_health():
    hostname = socket.gethostname()
    load1, load5, load15 = os.getloadavg()
    mem_total = 0
    mem_avail = 0
    try:
        with open("/proc/meminfo", "r", encoding="utf-8") as fh:
            for line in fh:
                if line.startswith("MemTotal:"):
                    mem_total = int(line.split()[1]) // 1024
                elif line.startswith("MemAvailable:"):
                    mem_avail = int(line.split()[1]) // 1024
    except Exception:
        pass

    statvfs = os.statvfs("/")
    disk_total_gb = round((statvfs.f_blocks * statvfs.f_frsize) / (1024 ** 3), 1)
    disk_free_gb = round((statvfs.f_bavail * statvfs.f_frsize) / (1024 ** 3), 1)

    allowed = sorted(ALLOWED_SERVICES_BY_ROLE.get(NODE_ROLE, DEFAULT_SERVICES))
    services = {}
    for svc in allowed:
        code, out, _ = run_cmd(["systemctl", "is-active", svc], timeout=5)
        services[svc] = out if code == 0 else (out or "inactive")

    role_metrics = {}
    if NODE_ROLE == "pg_ha":
        code, out, _ = run_cmd(["patronictl", "-c", "/etc/patroni/config.yml", "list", "-f", "json"], timeout=8)
        if code == 0 and out:
            try:
                role_metrics["patroni_members"] = json.loads(out)
            except Exception:
                role_metrics["patroni_raw"] = out[:400]
    elif NODE_ROLE == "storage_gluster":
        code, out, _ = run_cmd(["gluster", "volume", "list"], timeout=8)
        role_metrics["volumes"] = [v for v in out.splitlines() if v.strip()] if code == 0 else []
    elif NODE_ROLE == "pbx_telephony":
        code, out, _ = run_cmd(["fs_cli", "-x", "show channels count"], timeout=6)
        role_metrics["freeswitch_channels"] = out if code == 0 else "unavailable"
    elif NODE_ROLE == "sbc_edge":
        code_d, out_d, _ = run_cmd(["kamcmd", "dmq.list_nodes"], timeout=6)
        code_p, out_p, _ = run_cmd(["kamcmd", "dispatcher.list"], timeout=6)
        role_metrics["dmq_active_nodes"] = out_d.count("active") if code_d == 0 else 0
        role_metrics["dispatcher_active_ap"] = out_p.count("FLAGS: AP") if code_p == 0 else 0
    elif NODE_ROLE == "sbc_media":
        code_m, out_m, _ = run_cmd(["systemctl", "is-active", "ngcp-rtpengine-daemon"], timeout=5)
        role_metrics["media_relay_daemon"] = out_m if code_m == 0 else "inactive"
    elif NODE_ROLE == "video_sfu":
        code_v, out_v, _ = run_cmd(["systemctl", "is-active", "softswitch-video-sfu"], timeout=5)
        code_s, out_s, _ = run_cmd(["systemctl", "is-active", "softswitch-video-sip"], timeout=5)
        role_metrics["video_sfu_core"] = out_v if code_v == 0 else "inactive"
        role_metrics["video_sip_bridge"] = out_s if code_s == 0 else "inactive"

    return {
        "status": "ok",
        "hostname": hostname,
        "role": NODE_ROLE,
        "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "load_avg": [round(load1, 2), round(load5, 2), round(load15, 2)],
        "ram_total_mb": mem_total,
        "ram_avail_mb": mem_avail,
        "disk_total_gb": disk_total_gb,
        "disk_free_gb": disk_free_gb,
        "services": services,
        "role_metrics": role_metrics,
    }


def execute_emergency_action(action, params):
    if action == "reload_nftables":
        code, out, err = run_cmd(["nft", "-f", "/etc/nftables.conf"], timeout=15)
        return code == 0, out or err or "nftables ruleset reloaded"

    if action == "vacuum_journal":
        code, out, err = run_cmd(["journalctl", "--vacuum-size=100M"], timeout=20)
        return code == 0, out or err or "systemd journal vacuumed"

    if action == "patroni_switchover" and NODE_ROLE == "pg_ha":
        candidate = str(params.get("candidate", "")).strip()
        cmd = ["patronictl", "-c", "/etc/patroni/config.yml", "switchover", "--force"]
        if candidate and re.match(r"^[a-zA-Z0-9-]+$", candidate):
            cmd.extend(["--candidate", candidate])
        code, out, err = run_cmd(cmd, timeout=30)
        return code == 0, out or err

    if action == "freeswitch_reload_acl" and NODE_ROLE == "pbx_telephony":
        code, out, err = run_cmd(["fs_cli", "-x", "reloadacl"], timeout=15)
        return code == 0, out or err

    if action == "freeswitch_drain" and NODE_ROLE == "pbx_telephony":
        code, out, err = run_cmd(["fs_cli", "-x", "fsctl pause"], timeout=15)
        return code == 0, out or err

    if action == "freeswitch_resume" and NODE_ROLE == "pbx_telephony":
        code, out, err = run_cmd(["fs_cli", "-x", "fsctl resume"], timeout=15)
        return code == 0, out or err

    if action == "kamailio_reload_dispatchers" and NODE_ROLE == "sbc_edge":
        code, out, err = run_cmd(["kamcmd", "dispatcher.reload"], timeout=15)
        return code == 0, out or err

    if action == "kamailio_flush_auth_cache" and NODE_ROLE == "sbc_edge":
        code, out, err = run_cmd(["kamcmd", "htable.flush", "r2aAuth"], timeout=15)
        return code == 0, out or err

    if action == "sbc_ban_ip" and NODE_ROLE == "sbc_edge":
        ip = str(params.get("ip", "")).strip()
        if not SAFE_IP_RE.match(ip):
            return False, "Invalid IPv4/CIDR address"
        code, out, err = run_cmd(
            ["nft", "add", "rule", "inet", "filter", "input", "ip", "saddr", ip, "drop"],
            timeout=10,
        )
        return code == 0, out or err or f"Dropped traffic from {ip}"

    if action == "gluster_heal_full" and NODE_ROLE == "storage_gluster":
        outputs = []
        ok_all = True
        for vol in ("ss-recordings", "ss-uploads", "ss-music"):
            code, out, err = run_cmd(["gluster", "volume", "heal", vol, "info"], timeout=20)
            if code != 0:
                ok_all = False
            outputs.append(f"[{vol}] {out or err}")
        return ok_all, "\n".join(outputs)

    if action == "media_relay_restart" and NODE_ROLE == "sbc_media":
        code, out, err = run_cmd(["systemctl", "restart", "ngcp-rtpengine-daemon"], timeout=20)
        return code == 0, out or err or "Media Relay daemon restarted"

    if action == "video_sfu_restart" and NODE_ROLE == "video_sfu":
        code, out, err = run_cmd(
            ["systemctl", "restart", "softswitch-video-sfu", "softswitch-video-sip", "softswitch-video-egress"],
            timeout=25,
        )
        return code == 0, out or err or "Video SFU services restarted"

    return False, f"Action '{action}' is not permitted for role '{NODE_ROLE}'"


class NodeAgentHandler(http.server.BaseHTTPRequestHandler):
    server_version = "Ring2All-NodeAgent/1.0"

    def log_message(self, format, *args):
        return

    def _send_json(self, code, payload):
        raw = json.dumps(payload).encode("utf-8")
        self.send_response(code)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(raw)))
        self.end_headers()
        self.wfile.write(raw)

    def _authenticate(self):
        if not NODE_TOKEN:
            self._send_json(503, {"success": False, "error": "Agent token not configured"})
            return False
        presented = (self.headers.get("X-NMS-Node-Token") or "").strip()
        if not presented or not hmac.compare_digest(presented, NODE_TOKEN):
            self._send_json(401, {"success": False, "error": "Unauthorized"})
            return False
        return True

    def _read_json(self):
        length = int(self.headers.get("Content-Length", "0") or 0)
        if length <= 0 or length > 65536:
            return {}
        try:
            return json.loads(self.rfile.read(length).decode("utf-8"))
        except Exception:
            return {}

    def do_GET(self):
        if not self._authenticate():
            return
        if self.path == "/health":
            self._send_json(200, {"success": True, "data": collect_role_health()})
            return
        self._send_json(404, {"success": False, "error": "Not found"})

    def do_POST(self):
        if not self._authenticate():
            return
        body = self._read_json()

        if self.path == "/actions/service":
            service = str(body.get("service", "")).strip()
            operation = str(body.get("operation", "restart")).strip()
            allowed = ALLOWED_SERVICES_BY_ROLE.get(NODE_ROLE, DEFAULT_SERVICES)
            if service not in allowed:
                self._send_json(403, {"success": False, "error": f"Service '{service}' not allowed for role '{NODE_ROLE}'"})
                return
            if operation not in {"restart", "reload", "start", "stop", "status"}:
                self._send_json(400, {"success": False, "error": "Invalid systemctl operation"})
                return
            code, out, err = run_cmd(["systemctl", operation, service], timeout=30)
            self._send_json(200 if code == 0 else 500, {"success": code == 0, "output": out or err})
            return

        if self.path == "/actions/emergency":
            action = str(body.get("action", "")).strip()
            params = body.get("params") if isinstance(body.get("params"), dict) else {}
            ok, output = execute_emergency_action(action, params)
            self._send_json(200 if ok else 400, {"success": ok, "action": action, "output": output})
            return

        if self.path == "/actions/config-basic":
            results = []
            tz = str(body.get("timezone", "")).strip()
            if tz:
                if not SAFE_TZ_RE.match(tz):
                    self._send_json(400, {"success": False, "error": "Invalid timezone"})
                    return
                code, out, err = run_cmd(["timedatectl", "set-timezone", tz], timeout=10)
                results.append({"step": "timezone", "ok": code == 0, "detail": out or err or tz})

            hosts_lines = body.get("hosts_entries")
            if isinstance(hosts_lines, list) and hosts_lines:
                clean_lines = []
                for item in hosts_lines:
                    ip = str(item.get("ip", "")).strip()
                    host = str(item.get("hostname", "")).strip()
                    if SAFE_IP_RE.match(ip) and re.match(r"^[a-zA-Z0-9-]+$", host):
                        clean_lines.append(f"{ip} {host}")
                if clean_lines:
                    hosts_path = Path("/etc/hosts")
                    existing = hosts_path.read_text(encoding="utf-8")
                    cleaned = re.sub(
                        r"# BEGIN RING2ALL CLUSTER HOSTS[\s\S]*?# END RING2ALL CLUSTER HOSTS\n?",
                        "",
                        existing,
                    ).rstrip()
                    block = "\n# BEGIN RING2ALL CLUSTER HOSTS\n" + "\n".join(clean_lines) + "\n# END RING2ALL CLUSTER HOSTS\n"
                    hosts_path.write_text(cleaned + block, encoding="utf-8")
                    results.append({"step": "hosts_sync", "ok": True, "detail": f"Synced {len(clean_lines)} host entries"})

            self._send_json(200, {"success": True, "results": results})
            return

        self._send_json(404, {"success": False, "error": "Not found"})


def main():
    if not NODE_TOKEN:
        raise SystemExit("NMS_NODE_TOKEN is required")
    server = http.server.ThreadingHTTPServer((BIND_HOST, BIND_PORT), NodeAgentHandler)
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    ctx.load_cert_chain(certfile=TLS_CERT, keyfile=TLS_KEY)
    server.socket = ctx.wrap_socket(server.socket, server_side=True)
    server.serve_forever()


if __name__ == "__main__":
    main()
