"""Prepare the private missing-/bin/sh environment for scenarios:prove.
Usage: python3 prepare-shell-namespace.py REPO SCRATCH
Run scenarios:prove normally afterward. Requires passwordless sudo mount/unshare.
Only the real app command enters the namespace; the e2e runner stays on the host.
"""
import os
from pathlib import Path
import shlex
import shutil
import subprocess
import sys

repo, scratch = (Path(arg).resolve() for arg in sys.argv[1:])
scratch.mkdir(parents=True, exist_ok=True)
for name in ("upper", "overlay-work", "shell"):
    (scratch / name).mkdir(exist_ok=True)
shutil.copy("/usr/bin/dash", scratch / "shell/sh")
whiteout = scratch / "upper/sh"
if not whiteout.exists():
    subprocess.run(["sudo", "-n", "mknod", str(whiteout), "c", "0", "0"], check=True)
wrapper = scratch / "namespace-app.sh"
options = f"lowerdir=/usr/bin,upperdir={scratch}/upper,workdir={scratch}/overlay-work"
search_path = f"{scratch}/shell:{os.environ['PATH']}"
wrapper.write_text("\n".join([
    "#!/bin/bash", "set -eu", "mount --make-rprivate /",
    f"mount -t overlay overlay -o {shlex.quote(options)} /usr/bin",
    "test ! -e /bin/sh",
    f'exec runuser -u {shlex.quote(os.environ["USER"])} -p -- env PATH={shlex.quote(search_path)} "$@"',
    "",
]))
config = repo / "scripts/e2e.config.ts"
old = 'executable: resolved.node,\n          args: [startApp, "web", T3_HOME, LOOPBACK, "{port}"],'
import json
new = ('executable: "/usr/bin/sudo",\n          args: ["-n", "-E", "unshare", "-m", "bash", '
       + json.dumps(str(wrapper)) + ', resolved.node, startApp, "web", T3_HOME, LOOPBACK, "{port}"],')
source = config.read_text()
assert old in source, "Expected the original web app command"
config.write_text(source.replace(old, new))
