#!/usr/bin/env python3
"""Pindai seluruh situs klien (beranda + satu artikel) untuk mencari skrip suntikan yang sama."""
import importlib.util, os, re, time, urllib.error, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0 Safari/537.36"}
POLA = re.compile(r"livedashboardkit|35862e74a4a697bb6d998c471eade297|_b4a7b|_86b24|referrer\s*;?\s*if\s*\(!_", re.I)


def ambil(url):
    try:
        with urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=45) as x:
            return x.read().decode("utf-8", "replace")
    except Exception as e:
        return f"GAGAL {str(e)[:40]}"


KLIEN = []
for f in sorted(os.listdir(WS)):
    if f.startswith("cfg_") and f.endswith(".py"):
        try:
            spec = importlib.util.spec_from_file_location("c", f"{WS}/{f}")
            m = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(m)
            c = m.CFG
            if c.get("domain"):
                KLIEN.append((f[4:-3], c["domain"]))
        except Exception:
            continue

for nama, dom in KLIEN:
    # ambil satu artikel dari sitemap untuk diuji
    sm = ambil(f"https://{dom}/sitemap_index.xml")
    url_artikel = None
    if not sm.startswith("GAGAL"):
        sub = re.findall(r"<loc>([^<]+)</loc>", sm)[:3]
        for s in sub:
            t = ambil(s)
            if t.startswith("GAGAL"):
                continue
            cand = [u for u in re.findall(r"<loc>([^<]+)</loc>", t) if not u.rstrip("/").endswith((".xml", ".jpg", ".png"))]
            if cand:
                url_artikel = cand[0]
                break
    hasil = []
    for u in [f"https://{dom}/"] + ([url_artikel] if url_artikel else []):
        t = ambil(u)
        if t.startswith("GAGAL"):
            hasil.append("gagal")
            continue
        hasil.append("ADA" if POLA.search(t) else "-")
        time.sleep(0.4)
    tanda = " ⚠" if "ADA" in hasil else ""
    print(f"   {nama:<14} ({dom[:32]:<34}) beranda {hasil[0]:<6} artikel {hasil[1] if len(hasil)>1 else '-':<6}{tanda}")
    time.sleep(0.5)
