#!/usr/bin/env python3
"""DAS: cek sarana pengalihan 301 — plugin apa yang aktif, apakah Redirection/Yoast Premium ada."""
import base64, json, re, time, urllib.request, urllib.error, importlib.util

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg_das", f"{WS}/cfg_das.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
CFG = m.CFG
DOM, AUTH = CFG["domain"], base64.b64encode(f'{CFG["user"]}:{CFG["pass"]}'.encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}


def coba(p, method="GET", data=None):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    body = None
    if data is not None:
        body = json.dumps(data).encode(); h["Content-Type"] = "application/json"
    r = urllib.request.Request(f"https://{DOM}{p}", data=body, headers=h, method=method)
    try:
        with urllib.request.urlopen(r, timeout=120) as x:
            return x.status, x.read().decode("utf-8", "replace")[:400]
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode("utf-8", "replace")[:200]
    except Exception as e:
        return 0, str(e)[:120]


print("=== daftar plugin (butuh izin admin) ===")
st, isi = coba("/wp-json/wp/v2/plugins")
print(f"   status {st}")
if st == 200:
    try:
        for p in json.loads(isi):
            print(f"      {p.get('status'):<10} {p.get('name')} {p.get('version', '')}")
    except Exception:
        print("   " + isi[:200])
else:
    print("   " + isi[:160])

print("\n=== plugin yang tampak dari HTML beranda ===")
try:
    h = urllib.request.urlopen(urllib.request.Request(f"https://{DOM}/?v={int(time.time())}", headers=UA), timeout=120).read().decode("utf-8", "replace")
    for plug in sorted(set(re.findall(r"/wp-content/plugins/([a-z0-9\-_]+)/", h))):
        print("   " + plug)
except Exception as e:
    print("   gagal:", str(e)[:80])

print("\n=== cek rute REST Redirection / Yoast redirect ===")
for p in ("/wp-json/redirection/v1/redirect", "/wp-json/yoast/v1/redirects", "/wp-json/yoast/v1/get_head?url=/"):
    st, isi = coba(p)
    print(f"   {p[:44]:<46} status {st} | {isi[:80]}")

print("\n=== apakah sitemap memuat plugin redirect? ===")
try:
    h = urllib.request.urlopen(urllib.request.Request(f"https://{DOM}/sitemap_index.xml", headers=UA), timeout=120).read().decode("utf-8", "replace")
    print("   " + re.sub(r"\s+", " ", h)[:400])
except Exception as e:
    print("   gagal:", str(e)[:80])
