#!/usr/bin/env python3
"""Set a private root password before exposing staging MySQL on loopback."""

import json
import os
import subprocess

from create_private_credentials import TARGET, password


def main() -> None:
    values = json.loads(TARGET.read_text(encoding="utf-8"))
    source = values["SOURCE_MYSQL"]
    if "root_password" in source:
        raise SystemExit("Staging root password already recorded; refusing to replace it")
    root_password = password()
    sql = (
        f"UPDATE mysql.user SET Password=PASSWORD('{root_password}') WHERE User='root';\n"
        "FLUSH PRIVILEGES;\n"
    )
    result = subprocess.run(
        ["docker", "exec", "-i", "dm8-mysql56-newsource-20260928", "mysql"],
        input=sql,
        capture_output=True,
        text=True,
    )
    if result.returncode:
        raise SystemExit(f"Staging root credential change failed; exit={result.returncode}; stderr withheld")
    source["root_password"] = root_password
    temporary = TARGET.with_suffix(".tmp")
    fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    with os.fdopen(fd, "w", encoding="utf-8") as handle:
        json.dump(values, handle, ensure_ascii=False, indent=2)
        handle.write("\n")
    os.replace(temporary, TARGET)
    print("Isolated MySQL root account secured; secret withheld")


if __name__ == "__main__":
    main()
