#!/usr/bin/env python3
"""Periksa plugin mencurigakan (WP2P, Protect Uploads, Developer Toolkit, Quick SEO) di semua situs klien
dan cek apakah struktur URL-nya ikut berubah jadi .htm."""
import base64, importlib.util, json, os, time, urllib.error, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
UA = {"User-Agent": "Mozilla/5.0"}
MENCURIGAKAN = ("wp2p", "protect-uploads", "developer-toolkit", "advanced-backup", "starter-optimize")

KLIEN = []
for f in sorted(os.listdir(WS)):
    if not f.startswith("cfg_") or not f.endswith(".py"):
        continue
    nama = f[4:-3]
    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") and c.get("user") and c.get("pass"):
            KLIEN.append((nama, c["domain"], base64.b64encode(f"{c['user']}:{c['pass']}".encode()).decode()))
    except Exception:
        continue

print(f"situs diperiksa: {len(KLIEN)}\n")
for nama, dom, auth in KLIEN:
    h = {"Authorization": f"Basic {auth}", **UA}
    try:
        r = urllib.request.Request(f"https://{dom}/wp-json/wp/v2/plugins?per_page=100&_fields=plugin,name,status", headers=h)
        d = json.loads(urllib.request.urlopen(r, timeout=90).read())
    except urllib.error.HTTPError as e:
        print(f"■ {nama} ({dom}) → tidak bisa baca plugin (HTTP {e.code})")
        continue
    except Exception as e:
        print(f"■ {nama} ({dom}) → gagal ({str(e)[:40]})")
        continue
    curiga = [p for p in d if any(k in (p.get("plugin") or "").lower() for k in MENCURIGAKAN)]
    aktif = [p for p in curiga if p.get("status") == "active"]
    tanda = " ⚠" if aktif else ""
    print(f"■ {nama} ({dom}) · plugin {len(d)} · mencurigakan {len(curiga)} (aktif {len(aktif)}){tanda}")
    for p in curiga:
        print(f"     [{'AKTIF' if p.get('status')=='active' else 'mati '}] {p.get('name')} · {p.get('plugin')}")
    time.sleep(0.5)
