#!/usr/bin/env python3
"""Run from a current-main runner checkout; place this file beside the scenario copy.
Uses real OpenSSH, an isolated loopback sshd, generated keys and synthetic Git data.
No user SSH configuration, system configuration, or existing database is changed.
Requires passwordless sudo for the sshd process; listens on a random loopback port.
Usage: python3 run-proof.py /path/to/userless-ssh-repeated-slashes.e2e.ts
"""
import getpass, os, pathlib, socket, subprocess, sys, tempfile
root = pathlib.Path(tempfile.mkdtemp(prefix="ssh-proof-", dir=pathlib.Path(__file__).parent))
def run(args, **kw):
    return subprocess.run(args, check=True, **kw)
run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", str(root / "key")])
with socket.socket() as sock:
    sock.bind(("127.0.0.1", 0))
    port = sock.getsockname()[1]
(root / "sshd_config").write_text(f"""Port {port}
ListenAddress 127.0.0.1
HostKey {root}/key
PidFile {root}/sshd.pid
AuthorizedKeysFile {root}/key.pub
StrictModes no
PasswordAuthentication no
KbdInteractiveAuthentication no
UsePAM no
LogLevel ERROR
""")
(root / "ssh_config").write_text(f"""Host buildbox
 HostName localhost
 Port {port}
 User {getpass.getuser()}
 IdentityFile {root}/key
 UserKnownHostsFile {root}/known_hosts
 StrictHostKeyChecking accept-new
 BatchMode yes
""")
seed = root / "seed"
seed.mkdir()
run(["git", "init", "--quiet", "--initial-branch=main", str(seed)])
(seed / "README.md").write_text("Synthetic SSH repository identity proof.\n")
run(["git", "-C", str(seed), "add", "."])
run(["git", "-C", str(seed), "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-qm", "Initial commit"])
bare = root / "srv/git/repo.git"
bare.parent.mkdir(parents=True)
run(["git", "clone", "--bare", str(seed), str(bare)])
server = subprocess.Popen(["sudo", "-n", "/usr/sbin/sshd", "-D", "-e", "-f", str(root / "sshd_config")])
try:
    env = dict(os.environ, SSH_PROOF_FIXTURE=str(root), T3_SCENARIO_INHERIT_ENV="SSH_PROOF_FIXTURE", T3CODE_DEV_SEED="0")
    subprocess.run(["vp", "run", "scenarios:prove", sys.argv[1], "--base", "8613f47656ef5a2a75db0495d2f6579b239c03d1", "--head", "95d4f41494a385543f89048197255cc8a6ef79ed", "--upload-command", "ghdrop upload"], env=env, check=True)
finally:
    server.terminate()
    server.wait()
