#!/usr/bin/env python3
"""Cari sumber skrip suntikan di DAS: apakah ada di isi artikel, atau di plugin/tema."""
import base64, importlib.util, json, re, time, urllib.error, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg", f"{WS}/cfg_das.py")
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
CFG = m.CFG
DOM = CFG["domain"]
AUTH = base64.b64encode(f"{CFG['user']}:{CFG['pass']}".encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}
POLA = re.compile(r"livedashboardkit|35862e74a4a697bb6d998c471eade297|_b4a7b", re.I)


def rest(path):
    r = urllib.request.Request(f"https://{DOM}{path}", headers={"Authorization": f"Basic {AUTH}", **UA})
    for i in range(3):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return json.loads(x.read())
        except urllib.error.HTTPError as e:
            return {"err": e.code}
        except Exception:
            time.sleep(4)
    return {}


print("=== 1. apakah skrip ada di isi artikel/halaman? ===")
temuan = 0
for jenis in ("posts", "pages"):
    page = 1
    while True:
        d = rest(f"/wp-json/wp/v2/{jenis}?per_page=100&page={page}&status=publish&context=edit&_fields=id,slug,content")
        if not isinstance(d, list) or not d:
            break
        for x in d:
            if POLA.search(x["content"]["raw"]):
                temuan += 1
                print(f"   ⚠ #{x['id']} {jenis} /{x['slug'][:50]}")
        if len(d) < 100:
            break
        page += 1
print(f"   total konten yang memuat skrip: {temuan}")

print("\n=== 2. daftar plugin DAS ===")
pl = rest("/wp-json/wp/v2/plugins?per_page=100&_fields=plugin,name,version,status,author")
if isinstance(pl, list):
    for p in pl:
        print(f"   [{'AKTIF' if p.get('status')=='active' else 'mati '}] {str(p.get('name'))[:38]:<40} {p.get('version')} · {p.get('plugin')}")
else:
    print("   gagal:", str(pl)[:100])

print("\n=== 3. tema aktif ===")
th = rest("/wp-json/wp/v2/themes?status=active&_fields=stylesheet,name,version,author")
if isinstance(th, list):
    for x in th:
        print(f"   {x.get('name')} {x.get('version')} · {x.get('stylesheet')} · {x.get('author')}")
else:
    print("   gagal:", str(th)[:100])
