#!/usr/bin/env python3
import json
import subprocess
from pathlib import Path
sites = {}
for raw in Path('/etc/userdatadomains').read_text(errors='replace').splitlines():
parts = raw.split('==')
if len(parts) < 5 or ':' not in parts[0]:
continue
domain = parts[0].split(':', 1)[0].strip().lower().rstrip('.')
root = Path(parts[4].strip())
if (root / 'wp-config.php').is_file() and (root / 'wp-admin').is_dir():
sites.setdefault(str(root), domain)
root_text, domain = sorted(sites.items())[0]
root = Path(root_text)
managed = ''
try:
text = (root / '.htaccess').read_text(errors='replace')
start = text.find('# BEGIN wp-MM-System request protection')
end = text.find('# END wp-MM-System request protection')
managed = text[start:end + len('# END wp-MM-System request protection')] if start >= 0 and end >= 0 else ''
except Exception as exc:
managed = 'ERROR: ' + str(exc)
tests = {}
for path in ('/', '/xmlrpc.php', '/wp-admin/setup-config.php', '/wp-admin/about.php', '/wp-admin/wpmm-not-found.php'):
cmd = ['curl', '-sS', '-D', '-', '-H', 'Host: ' + domain, '-o', '/tmp/wpmm-curl-body', '--max-time', '10', 'http://127.0.0.1' + path]
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
headers = result.stdout.replace('\r', '').split('\n')
body = Path('/tmp/wpmm-curl-body').read_text(errors='replace')[:160] if Path('/tmp/wpmm-curl-body').exists() else ''
tests[path] = {'status': headers[0] if headers else '', 'server': next((x for x in headers if x.lower().startswith('server:')), ''), 'location': next((x for x in headers if x.lower().startswith('location:')), ''), 'body': body.replace('\n', ' ')}
print(json.dumps({'domain': domain, 'root': str(root), 'managed_block': managed, 'tests': tests}, ensure_ascii=False))