"""Synthetic local SSH fixture used by proof-driver.cjs. Requires sudo and OpenSSH."""
import os
from pathlib import Path
import shutil
import subprocess

scratch = Path(os.environ['PROOF_SCRATCH'])
stock_node = Path(os.environ['PROOF_NODE_24'])  # stock Node 24.22.2
scratch.mkdir(parents=True, exist_ok=True)
fixture = scratch / 'fixture'
(fixture / 'bin').mkdir(parents=True, exist_ok=True)
shutil.copy2(stock_node, fixture / 'node-real')
(fixture / 'preload.cjs').write_text("Object.defineProperty(process.versions, 'node', {value: '24.22.2+vendor.1'});\n")
(fixture / 'bin/node').write_text(f'#!/bin/sh\nexec {fixture}/node-real --require {fixture}/preload.cjs "$@"\n')
(fixture / 'bin/node').chmod(0o755)
for side in ['base', 'head']:
    home = scratch / f'remote-{side}'
    home.mkdir(exist_ok=True)
    (home / '.bashrc').write_text(f'export PATH={fixture}/bin:/usr/local/bin:/usr/bin:/bin\nexport T3CODE_ENVIRONMENT_LABEL="SSH Node fixture"\n')
    (home / '.profile').write_text('. "$HOME/.bashrc"\n')
subprocess.run(['sudo', '-n', 'useradd', '-M', '-d', str(scratch / 'remote-base'), '-s', '/bin/bash', 'ssh-proof'], check=True)
subprocess.run(['sudo', '-n', 'usermod', '-p', '*', 'ssh-proof'], check=True)
# The account must be able to traverse the checkout and read its built server.
subprocess.run(['sudo', '-n', 'usermod', '-aG', str(os.getgid()), 'ssh-proof'], check=True)
for side in ['base', 'head']:
    subprocess.run(['sudo', '-n', 'chown', '-R', 'ssh-proof:ssh-proof', str(scratch / f'remote-{side}')], check=True)
for key in ['client-key', 'host-key']:
    subprocess.run(['ssh-keygen', '-q', '-t', 'ed25519', '-N', '', '-f', str(scratch / key)], check=True)
(scratch / 'clientbin').mkdir(exist_ok=True)
ssh = scratch / 'clientbin/ssh'
ssh.write_text(f'#!/bin/sh\nexec /usr/bin/ssh -i {scratch}/client-key -o IdentitiesOnly=yes -o UserKnownHostsFile={scratch}/known_hosts -o StrictHostKeyChecking=accept-new "$@"\n')
ssh.chmod(0o755)
(scratch / 'sshd.conf').write_text(f'''Port 2242
ListenAddress 127.0.0.1
HostKey {scratch}/host-key
PidFile {scratch}/sshd.pid
AuthorizedKeysFile {scratch}/client-key.pub
StrictModes no
PasswordAuthentication no
UsePAM no
AllowUsers ssh-proof
LogLevel ERROR
''')
print('Start: sudo -n /usr/sbin/sshd -D -e -f "$PROOF_SCRATCH/sshd.conf"')
