#!/bin/bash
# ==============================================================================
# install-ring2all-motd.sh — Classic Unix Dynamic SSH Welcome Banner
# Installs /etc/update-motd.d/00-ring2all
# Supports: PBX, SBC, BSS, DMS, NMS, NCX, CRM, VIDEO, HUB (auto-detection)
#
# Usage:
#   bash install-ring2all-motd.sh [AUTO|PBX|SBC|BSS|DMS|NMS|NCX|CRM|VIDEO|HUB]
# ==============================================================================
set -e

ROLE_ARG="${1:-AUTO}"
ROLE_UPPER=$(echo "${ROLE_ARG}" | tr '[:lower:]' '[:upper:]')

mkdir -p /etc/softswitch /etc/update-motd.d

if [ "${ROLE_UPPER}" != "AUTO" ] && [ -n "${ROLE_UPPER}" ]; then
    echo "${ROLE_UPPER}" > /etc/softswitch/motd-role
    chmod 644 /etc/softswitch/motd-role
elif [ ! -f /etc/softswitch/motd-role ]; then
    echo "AUTO" > /etc/softswitch/motd-role
    chmod 644 /etc/softswitch/motd-role
fi

# Silence Debian's static legal notice and duplicate 10-uname line
if [ -s /etc/motd ] && [ ! -f /etc/motd.debian.orig ]; then
    cp /etc/motd /etc/motd.debian.orig 2>/dev/null || true
fi
: > /etc/motd
chmod 644 /etc/motd 2>/dev/null || true
chmod -x /etc/update-motd.d/10-uname 2>/dev/null || true

cat << 'MOTD_EOF' > /etc/update-motd.d/00-ring2all
#!/usr/bin/env python3
"""Ring2All Platform Classic Unix Dynamic SSH Login MOTD Generator."""

import os
import re
import socket
import subprocess

NO_COLOR = bool(os.environ.get("NO_COLOR"))

ESC = "\033["
RESET = "" if NO_COLOR else f"{ESC}0m"
BOLD = "" if NO_COLOR else f"{ESC}1m"
MUTED = "" if NO_COLOR else f"{ESC}38;5;244m"
RULE = "" if NO_COLOR else f"{ESC}38;5;240m"
GREEN = "" if NO_COLOR else f"{ESC}38;5;42m"
YELLOW = "" if NO_COLOR else f"{ESC}38;5;214m"
RED = "" if NO_COLOR else f"{ESC}38;5;203m"

WIDTH = 74
LEFT_W = 39
LABEL_W = 10
VAL_W = LEFT_W - LABEL_W  # 29 chars (fits full hostname, IP, kernel, load, mem, disk)


def ansi(code):
    return "" if NO_COLOR else f"{ESC}38;5;{code}m"


APPS = {
    "PBX": {
        "color": ansi(99),
        "tagline": "Class 5 Cloud Softswitch & AI Telephony",
        "pkg": "softswitch-pbx-admin",
        "services": [
            ("freeswitch", ["freeswitch"], "SIP/RTP", True),
            ("softswitch-api", ["softswitch-api", "softswitch-pbx-api"], ":3001 REST", True),
            ("monitoring-api", ["softswitch-monitoring-api"], ":3500 ESL", False),
            ("postgresql", ["postgresql@17-main", "postgresql"], "DB", False),
            ("nginx", ["nginx"], "HTTP/2", True),
            ("fail2ban", ["fail2ban"], "Intrusion", False),
            ("nftables", ["nftables"], "Firewall", False),
        ],
    },
    "SBC": {
        "color": ansi(33),
        "tagline": "Session Border Controller & Edge Security",
        "pkg": "softswitch-sbc-admin",
        "services": [
            ("kamailio", ["kamailio"], ":5060/:5061", True),
            ("rtpengine", ["ngcp-rtpengine-daemon", "rtpengine"], "Media Relay", True),
            ("sbc-api", ["sbc-api", "softswitch-sbc-api"], ":3003 REST", True),
            ("postgresql", ["postgresql@17-main", "postgresql"], "DB", False),
            ("nginx", ["nginx"], "HTTP/2", True),
            ("fail2ban", ["fail2ban"], "Intrusion", False),
            ("nftables", ["nftables"], "Firewall", False),
        ],
    },
    "BSS": {
        "color": ansi(42),
        "tagline": "Converged Billing, Real-Time OCS & Store",
        "pkg": "softswitch-bss-web",
        "services": [
            ("softswitch-bss", ["softswitch-bss-api"], ":3002 OCS", True),
            ("postgresql", ["postgresql@17-main", "postgresql"], "DB", False),
            ("nginx", ["nginx"], "HTTP/2", True),
            ("redis-server", ["redis-server", "redis"], "Rate cache", False),
            ("fail2ban", ["fail2ban"], "Intrusion", False),
            ("nftables", ["nftables"], "Firewall", False),
        ],
    },
    "DMS": {
        "color": ansi(69),
        "tagline": "Device Management & ZTP Auto-Provisioning",
        "pkg": "softswitch-dms-web",
        "services": [
            ("softswitch-dms", ["softswitch-dms-api"], ":3000 REST", True),
            ("postgresql", ["postgresql@17-main", "postgresql"], "ss_dms", False),
            ("nginx", ["nginx"], "HTTP/2", True),
            ("tftpd-hpa", ["tftpd-hpa"], "UDP :69 TFTP", False),
            ("fail2ban", ["fail2ban"], "Intrusion", False),
            ("nftables", ["nftables"], "Firewall", False),
        ],
    },
    "NMS": {
        "color": ansi(39),
        "tagline": "Neural Monitoring System & Fleet Watchdog",
        "pkg": "softswitch-nms-web",
        "services": [
            ("softswitch-nms", ["softswitch-nms-api"], ":3005 REST", True),
            ("postgresql", ["postgresql@17-main", "postgresql"], "ss_nms", False),
            ("nginx", ["nginx"], "HTTP/2", True),
            ("snmpd", ["snmpd"], "SNMP agent", False),
            ("fail2ban", ["fail2ban"], "Intrusion", False),
            ("nftables", ["nftables"], "Firewall", False),
        ],
    },
    "NCX": {
        "color": ansi(208),
        "tagline": "Neural Customer Experience (CCaaS & Dialer)",
        "pkg": "softswitch-ncx-web",
        "services": [
            ("ncx-api", ["softswitch-ncx-api"], ":3008 REST", True),
            ("ncx-worker", ["softswitch-ncx-worker"], "ACD/Dialer", False),
            ("ncx-stt", ["softswitch-ncx-stt"], "Speech AI", False),
            ("postgresql", ["postgresql@17-main", "postgresql"], "DB", False),
            ("nginx", ["nginx"], "HTTP/2", True),
            ("fail2ban", ["fail2ban"], "Intrusion", False),
            ("nftables", ["nftables"], "Firewall", False),
        ],
    },
    "CRM": {
        "color": ansi(37),
        "tagline": "AI-First CRM, Kanban Pipelines & Helpdesk",
        "pkg": "softswitch-crm-web",
        "services": [
            ("crm-api", ["softswitch-crm-api"], ":3008 REST", True),
            ("postgresql", ["postgresql@17-main", "postgresql"], "ss_crm", False),
            ("nginx", ["nginx"], "HTTP/2", True),
            ("fail2ban", ["fail2ban"], "Intrusion", False),
            ("nftables", ["nftables"], "Firewall", False),
        ],
    },
    "VIDEO": {
        "color": ansi(135),
        "tagline": "WebRTC SFU Conferencing & SIP Video Gateway",
        "pkg": "softswitch-video-sfu",
        "services": [
            ("livekit-sfu", ["livekit-server"], ":7880 SFU", True),
            ("livekit-sip", ["livekit-sip"], "SIP Bridge", False),
            ("livekit-egress", ["livekit-egress"], "Recording", False),
            ("redis-server", ["redis-server", "redis"], "Signaling", False),
            ("nginx", ["nginx"], "HTTP/2", False),
            ("fail2ban", ["fail2ban"], "Intrusion", False),
            ("nftables", ["nftables"], "Firewall", False),
        ],
    },
    "HUB": {
        "color": ansi(39),
        "tagline": "Ring2All Platform Cluster Node",
        "pkg": "softswitch-pbx-admin",
        "services": [
            ("freeswitch", ["freeswitch"], "SIP/RTP", False),
            ("kamailio", ["kamailio"], ":5060/:5061", False),
            ("rtpengine", ["ngcp-rtpengine-daemon", "rtpengine"], "Media Relay", False),
            ("softswitch-api", ["softswitch-api", "softswitch-pbx-api"], ":3001 PBX", False),
            ("monitoring-api", ["softswitch-monitoring-api"], ":3500 ESL", False),
            ("sbc-api", ["sbc-api", "softswitch-sbc-api"], ":3003 SBC", False),
            ("softswitch-bss", ["softswitch-bss-api"], ":3002 BSS", False),
            ("softswitch-dms", ["softswitch-dms-api"], ":3000 DMS", False),
            ("softswitch-nms", ["softswitch-nms-api"], ":3005 NMS", False),
            ("ncx-api", ["softswitch-ncx-api"], ":3008 CCaaS", False),
            ("ncx-worker", ["softswitch-ncx-worker"], "ACD/Dialer", False),
            ("crm-api", ["softswitch-crm-api"], ":3008 CRM", False),
            ("livekit-sfu", ["livekit-server"], ":7880 Video", False),
            ("postgresql", ["postgresql@17-main", "postgresql"], "Cluster", False),
            ("haproxy", ["haproxy"], "DB Proxy", False),
            ("glusterd", ["glusterd"], "Shared FS", False),
            ("redis-server", ["redis-server", "redis"], "Cache", False),
            ("nginx", ["nginx"], "HTTP/2", False),
            ("fail2ban", ["fail2ban"], "Intrusion", False),
            ("nftables", ["nftables"], "Firewall", False),
        ],
    },
}


def run_out(cmd):
    try:
        return subprocess.check_output(cmd, stderr=subprocess.DEVNULL, text=True, timeout=1.5).strip()
    except Exception:
        return ""


def pad(text, width):
    if len(text) > width:
        return text[: max(0, width - 1)] + "…" if width >= 1 else ""
    return text + (" " * (width - len(text)))


def get_dpkg_versions():
    pkgs = [
        "softswitch-pbx-admin", "softswitch-pbx-api", "softswitch-pbx-portal", "softswitch-pbx-switchboard",
        "softswitch-sbc-admin", "softswitch-sbc-api",
        "softswitch-bss-web", "softswitch-bss-api", "softswitch-bss-client",
        "softswitch-dms-web", "softswitch-dms-api",
        "softswitch-nms-web", "softswitch-nms-api",
        "softswitch-ncx-web", "softswitch-ncx-api", "softswitch-ncx-worker",
        "softswitch-crm-web", "softswitch-crm-api",
        "softswitch-video-sfu",
        "nginx", "postgresql-17", "freeswitch", "kamailio", "ngcp-rtpengine-daemon",
    ]
    vers = {}
    try:
        res = subprocess.run(
            ["dpkg-query", "-W", "-f=${Package}\t${Status}\t${Version}\n"] + pkgs,
            capture_output=True, text=True, timeout=1.5
        )
        for line in res.stdout.splitlines():
            parts = line.split("\t")
            if len(parts) == 3 and "install ok installed" in parts[1]:
                vers[parts[0]] = parts[2]
    except Exception:
        pass
    return vers


def get_unit_info(units):
    """Return {unit: (load_state, active_state, unit_file_state)} via batched systemctl show."""
    info = {u: ("unknown", "unknown", "unknown") for u in units}
    if not units:
        return info
    try:
        res = subprocess.run(
            ["systemctl", "show", "-p", "Id,LoadState,ActiveState,UnitFileState"] + [f"{u}.service" for u in units],
            capture_output=True, text=True, timeout=1.5
        )
        blocks = [b for b in res.stdout.strip().split("\n\n") if b.strip()]
        for idx, block in enumerate(blocks):
            if idx >= len(units):
                break
            kv = {}
            for line in block.splitlines():
                if "=" in line:
                    k, v = line.split("=", 1)
                    kv[k.strip()] = v.strip()
            info[units[idx]] = (
                kv.get("LoadState", "unknown"),
                kv.get("ActiveState", "unknown"),
                kv.get("UnitFileState", "unknown"),
            )
    except Exception:
        pass
    return info


def clean_ver(raw, prefix_v=True):
    if not raw:
        return ""
    ver = raw.split("-")[0].split("+")[0].split("~")[0].strip()
    return f"v{ver}" if prefix_v and ver and not ver.startswith("v") else ver


def detect_role(vers, states):
    role_file = "/etc/softswitch/motd-role"
    if os.path.isfile(role_file):
        try:
            saved = open(role_file, encoding="utf-8").read().strip().upper()
            if saved in APPS:
                return saved
        except Exception:
            pass

    if "softswitch-pbx-admin" in vers or "softswitch-pbx-api" in vers or "freeswitch" in vers:
        return "PBX"
    if "softswitch-sbc-admin" in vers or "softswitch-sbc-api" in vers or "kamailio" in vers:
        return "SBC"
    if "softswitch-bss-web" in vers or "softswitch-bss-api" in vers or "softswitch-bss-client" in vers:
        return "BSS"
    if "softswitch-dms-web" in vers or "softswitch-dms-api" in vers:
        return "DMS"
    if "softswitch-nms-web" in vers or "softswitch-nms-api" in vers:
        return "NMS"
    if "softswitch-ncx-web" in vers or "softswitch-ncx-api" in vers:
        return "NCX"
    if "softswitch-crm-web" in vers or "softswitch-crm-api" in vers:
        return "CRM"
    if "softswitch-video-sfu" in vers or states.get("livekit-server", ("", "", ""))[0] == "loaded":
        return "VIDEO"
    if os.path.isdir("/var/www/ring2all-crm"):
        return "CRM"
    if os.path.isdir("/var/www/softswitch/sbc"):
        return "SBC"
    if os.path.isdir("/var/www/softswitch/bss"):
        return "BSS"
    if os.path.isdir("/var/www/ring2all-dms"):
        return "DMS"
    if os.path.isdir("/var/www/ring2all-nms"):
        return "NMS"
    return "PBX"


def get_primary_ip():
    out = run_out(["hostname", "-I"])
    if out:
        for tok in out.split():
            if "." in tok and not tok.startswith("127."):
                return tok
    return "127.0.0.1"


def get_os_info():
    pretty = "Debian GNU/Linux 13 (trixie)"
    try:
        with open("/etc/os-release", encoding="utf-8") as fh:
            for line in fh:
                if line.startswith("PRETTY_NAME="):
                    pretty = line.split("=", 1)[1].strip().strip('"')
                    break
    except Exception:
        pass
    pretty = pretty.replace("Debian GNU/Linux ", "Debian ")
    short_os = re.sub(r"\s*\([^)]*\)\s*", " ", pretty).strip()
    return short_os, os.uname().machine


def get_mem():
    try:
        info = {}
        with open("/proc/meminfo", encoding="utf-8") as fh:
            for line in fh:
                k, v = line.split(":", 1)
                info[k] = int(v.strip().split()[0])
        total_kb = info.get("MemTotal", 0)
        avail_kb = info.get("MemAvailable", info.get("MemFree", 0))
        used_kb = max(0, total_kb - avail_kb)
        pct = int(round((used_kb / total_kb) * 100)) if total_kb else 0
        if total_kb >= 1048576:
            return f"{used_kb / 1048576:.1f} / {total_kb / 1048576:.1f} GiB ({pct}%)"
        return f"{used_kb // 1024} / {total_kb // 1024} MiB ({pct}%)"
    except Exception:
        return "n/a"


def get_disk():
    try:
        st = os.statvfs("/")
        total = st.f_blocks * st.f_frsize
        free = st.f_bavail * st.f_frsize
        used = max(0, (st.f_blocks - st.f_bfree) * st.f_frsize)
        usable = used + free
        pct = int(round((used / usable) * 100)) if usable else 0
        gib = 1024 ** 3
        return f"{used / gib:.1f} / {total / gib:.1f} GiB ({pct}%)"
    except Exception:
        return "n/a"


def get_uptime():
    try:
        secs = int(float(open("/proc/uptime", encoding="utf-8").read().split()[0]))
        days, rem = divmod(secs, 86400)
        hrs, rem = divmod(rem, 3600)
        mins = rem // 60
        if days > 0:
            return f"{days}d {hrs:02d}h {mins:02d}m"
        return f"{hrs:02d}h {mins:02d}m"
    except Exception:
        return "n/a"


def get_load():
    try:
        l1, l5, l15 = open("/proc/loadavg", encoding="utf-8").read().split()[:3]
        cpus = os.cpu_count() or 1
        return f"{cpus} vCPU · {l1}, {l5}, {l15}"
    except Exception:
        return "n/a"


def main():
    vers = get_dpkg_versions()

    all_units = []
    for cfg in APPS.values():
        for _, candidates, _, _ in cfg["services"]:
            all_units.extend(candidates)
    all_units.extend([
        "softswitch-ncx-api", "softswitch-ncx-worker",
        "livekit-server", "redis-server", "haproxy", "glusterd",
    ])
    unit_info = get_unit_info(sorted(set(all_units)))

    role = detect_role(vers, unit_info)
    cfg = APPS[role]
    c = cfg["color"]

    host = socket.gethostname()
    ip = get_primary_ip()
    os_short, arch = get_os_info()
    kernel = os.uname().release

    pkg_ver = vers.get(cfg["pkg"], "")
    if not pkg_ver:
        for k, v in vers.items():
            if k.startswith("softswitch-") and v:
                pkg_ver = v
                break

    meta_parts = [p for p in (f"v{pkg_ver}" if pkg_ver else "", os_short, arch) if p]
    right_meta = " · ".join(meta_parts)
    left_plain = f"RING2ALL · {role}"
    head_gap = max(2, WIDTH - len(left_plain) - len(right_meta))

    hr = f"  {RULE}{'─' * WIDTH}{RESET}"

    out = [
        "",
        f"  {BOLD}RING2ALL{RESET} {MUTED}·{RESET} {BOLD}{c}{role}{RESET}{' ' * head_gap}{MUTED}{right_meta}{RESET}",
        f"  {MUTED}{cfg['tagline']}{RESET}",
        hr,
    ]

    hw_rows = [
        ("Host", host),
        ("Address", ip),
        ("Kernel", kernel),
        ("CPU/Load", get_load()),
        ("Memory", get_mem()),
        ("Disk /", get_disk()),
        ("Uptime", get_uptime()),
    ]

    svc_rows = []
    nginx_ver = clean_ver(vers.get("nginx", ""))
    pg_ver = clean_ver(vers.get("postgresql-17", ""))
    fs_ver = clean_ver(vers.get("freeswitch", ""))
    kam_ver = clean_ver(vers.get("kamailio", ""))
    rtp_ver = clean_ver(vers.get("ngcp-rtpengine-daemon", ""))

    extra_svcs = []
    if role == "PBX":
        if "softswitch-ncx-api" in vers or unit_info.get("softswitch-ncx-api", ("", "", ""))[0] == "loaded":
            extra_svcs.append(("ncx-api", ["softswitch-ncx-api"], ":3008 CCaaS", False))
        if "softswitch-ncx-worker" in vers or unit_info.get("softswitch-ncx-worker", ("", "", ""))[0] == "loaded":
            extra_svcs.append(("ncx-worker", ["softswitch-ncx-worker"], "ACD/Dialer", False))
        if "softswitch-video-sfu" in vers or unit_info.get("livekit-server", ("", "", ""))[0] == "loaded":
            extra_svcs.append(("livekit-sfu", ["livekit-server"], ":7880 Video", False))

    candidates_list = list(cfg["services"]) + extra_svcs
    for label, units, suffix, required in candidates_list:
        any_loaded = any(unit_info.get(u, ("unknown", "unknown", "unknown"))[0] == "loaded" for u in units)
        if not required and not any_loaded:
            continue
        if label == "nftables" and not any(
            unit_info.get(u, ("", "", ""))[1] in ("active", "activating", "reloading", "failed")
            or unit_info.get(u, ("", "", ""))[2] == "enabled"
            for u in units
        ):
            continue

        state = "inactive"
        for u in units:
            load_st, active_st, _ = unit_info.get(u, ("unknown", "unknown", "unknown"))
            if active_st == "active":
                state = "active"
                break
            if active_st in ("activating", "reloading") and state == "inactive":
                state = active_st
            elif active_st == "failed":
                state = "failed"
            elif load_st == "not-found" and state == "inactive":
                state = "not-found"

        detail = suffix
        if label == "nginx" and nginx_ver:
            detail = f"{nginx_ver} · {suffix}" if suffix != "HTTP/2" else f"{nginx_ver} HTTP/2"
        elif label == "postgresql" and pg_ver:
            detail = f"{pg_ver} · {suffix}" if suffix != "DB" else pg_ver
        elif label == "freeswitch" and fs_ver:
            detail = f"{fs_ver} · SIP"
        elif label == "kamailio" and kam_ver:
            detail = f"{kam_ver} · :5060"
        elif label == "rtpengine" and rtp_ver:
            detail = f"{rtp_ver} Media"

        if state == "active":
            dot_color = GREEN
            status_str = f"{MUTED}{detail}{RESET}"
        elif state in ("activating", "reloading"):
            dot_color = YELLOW
            status_str = f"{YELLOW}{state}{RESET} {MUTED}({detail}){RESET}"
        else:
            dot_color = RED
            status_str = f"{BOLD}{RED}{state}{RESET} {MUTED}({detail}){RESET}"

        svc_rows.append((label, status_str, dot_color))

    out.append(f"  {c}{pad('SYSTEM', LEFT_W)}{RESET}{c}SERVICES{RESET}")

    max_rows = max(len(hw_rows), len(svc_rows))
    for idx in range(max_rows):
        if idx < len(hw_rows):
            hk, hv = hw_rows[idx]
            left = f"{MUTED}{pad(hk, LABEL_W)}{RESET}{pad(hv, VAL_W)}"
        else:
            left = " " * LEFT_W

        if idx < len(svc_rows):
            sk, s_detail, dot_c = svc_rows[idx]
            right = f"{dot_c}●{RESET} {pad(sk, 15)} {s_detail}"
        else:
            right = ""

        out.append(f"  {left}{right}".rstrip())

    if role == "PBX":
        extras = []
        if "softswitch-pbx-portal" in vers or os.path.isdir("/var/www/softswitch/portal"):
            extras.append("/connect/")
        if "softswitch-pbx-switchboard" in vers or os.path.isdir("/var/www/softswitch/switchboard"):
            extras.append("/switchboard")
        web_line = f"https://{ip}" + (f"  ({' · '.join(extras)})" if extras else "")
        cli_line = "ss_cmd health · pbx-cli · mcp-assistant --status · r2a-fail2ban"
    elif role == "SBC":
        web_line = f"https://{ip}  (Kamailio + RTPEngine Edge Console)"
        cli_line = "sbc_cmd status · kamcmd dispatcher.list · sbc-mcp --status"
    elif role == "BSS":
        web_line = f"Admin: https://{ip} · Store: https://{ip}:8443"
        cli_line = "curl -s localhost:3002/health · journalctl -u softswitch-bss-api"
    elif role == "DMS":
        web_line = f"https://{ip}  (/cfg/{{mac}})"
        cli_line = "curl -s localhost:3000/api/health · journalctl -u softswitch-dms-api"
    elif role == "NMS":
        web_line = f"https://{ip}  (NMS Dashboard & Telemetry)"
        cli_line = "curl -s localhost:3005/api/health · journalctl -u softswitch-nms-api"
    elif role == "NCX":
        web_line = f"https://{ip}:8089  (/connect/ncx-console)"
        cli_line = "curl -s localhost:3008/health · journalctl -u softswitch-ncx-api"
    elif role == "CRM":
        web_line = f"https://{ip}  (CRM & Helpdesk Console)"
        cli_line = "curl -s localhost:3008/health · journalctl -u softswitch-crm-api"
    elif role == "VIDEO":
        web_line = f"https://{ip}  (LiveKit SFU WebRTC)"
        cli_line = "systemctl status livekit-server · journalctl -u livekit-server"
    else:
        if unit_info.get("nginx", ("", "", ""))[0] == "loaded":
            web_line = f"https://{ip}"
            cli_line = "systemctl list-units 'softswitch-*' · nginx -t"
        else:
            web_line = "n/a (Backend / Database Cluster Node)"
            cli_line = "systemctl list-units 'softswitch-*' 'postgresql*'"

    out.append(hr)
    out.append(f"  {MUTED}{pad('Web UI', LABEL_W)}{RESET}{BOLD}{web_line}{RESET}")
    out.append(f"  {MUTED}{pad('CLI', LABEL_W)}{RESET}{MUTED}{cli_line}{RESET}")
    out.append("")

    print("\n".join(out))


if __name__ == "__main__":
    main()
MOTD_EOF

chmod 755 /etc/update-motd.d/00-ring2all
