#!/usr/bin/env python3
"""Install a disposable WordPress target with an unrecoverable random owner password."""

from __future__ import annotations

import argparse
import secrets
import urllib.parse
import urllib.request


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("base_url")
    args = parser.parse_args()
    base = args.base_url.rstrip("/")
    password = "Owner!" + secrets.token_urlsafe(48)
    body = urllib.parse.urlencode(
        {
            "weblog_title": "Pruva isolated source lab",
            "user_name": "owner",
            "admin_password": password,
            "admin_password2": password,
            "pw_weak": "1",
            "admin_email": "owner@invalid.test",
            "blog_public": "0",
            "Submit": "Install WordPress",
            "language": "",
        }
    ).encode()
    request = urllib.request.Request(
        base + "/wp-admin/install.php?step=2",
        data=body,
        headers={"Content-Type": "application/x-www-form-urlencoded"},
    )
    with urllib.request.urlopen(request, timeout=30) as response:
        page = response.read().decode(errors="replace")
    if "WordPress has been installed" not in page:
        raise SystemExit("WordPress installation did not complete")
    # Deliberately do not print or persist the owner password.
    print("installed_with_unrecoverable_random_owner_password=true")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
