"""Run with a fresh scratch directory argument; requires passwordless sudo and OpenSSH.
Starts only a loopback SSH endpoint, with password auth disabled and an isolated filesystem.
The caller must stop the printed sshd PID and remove the fresh directory afterwards.
"""
import os, pathlib, re, shutil, subprocess, sys
p = pathlib.Path(sys.argv[1]).resolve()
p.mkdir(parents=True, exist_ok=True)
r = p / 'ssh-root'
r.mkdir(exist_ok=True)
for executable in ['/bin/sh', '/bin/bash']:
    files = [executable] + re.findall(r'(/[^\s()]+)', subprocess.check_output(['ldd', executable], text=True))
    for source in files:
        dest = r / source.lstrip('/')
        dest.parent.mkdir(parents=True, exist_ok=True)
        shutil.copyfile(source, dest)
        dest.chmod(0o755)
(r / 'dev').mkdir(exist_ok=True)
subprocess.run(['sudo', 'mknod', '-m', '666', str(r / 'dev/null'), 'c', '1', '3'], check=True)
for key in ['identity', 'host_key']:
    subprocess.run(['ssh-keygen', '-q', '-t', 'ed25519', '-N', '', '-C', 'SSH prerequisite fixture', '-f', str(p / key)], check=True)
user = os.environ['USER']
config = p / 'sshd_config'
config.write_text(f'''Port 22498
ListenAddress 127.0.0.1
HostKey {p}/host_key
PidFile {p}/sshd.pid
AuthorizedKeysFile {p}/identity.pub
PasswordAuthentication no
KbdInteractiveAuthentication no
UsePAM no
StrictModes no
AllowUsers {user}
ForceCommand sudo /usr/sbin/chroot {r} /bin/bash -c "$SSH_ORIGINAL_COMMAND"
LogLevel ERROR
''')
log = open(p / 'sshd.log', 'w')
server = subprocess.Popen(['sudo', '/usr/sbin/sshd', '-D', '-e', '-f', str(config)], stdout=log, stderr=log)
print('sshd PID:', server.pid)
print('Add identity to a temporary ssh-agent, trust the loopback host key, and pass SSH_AUTH_SOCK to e2e app.command.inheritEnv.')
print('Set PROOF_SSH_ROOT to ssh-root, PROOF_FIXTURE_SCRIPT to ssh-fixture.py, PROOF_NODE_OLD to a Node <22 binary, and PROOF_NODE_SUPPORTED to Node >=22.')
