#!/usr/bin/env python3
"""Create an isolated user-run SSH fixture; generates fresh local-only keys.
Usage: python3 fixture.py /absolute/scratch/fixture
Start: /usr/sbin/sshd -D -e -f <fixture>/sshd_config
Proxy: socat TCP-LISTEN:40001,bind=127.0.0.1,reuseaddr,fork TCP:127.0.0.1:22999
Launch the desktop with <fixture>/bin prepended to PATH, T3CODE_DEV_SEED=0,
T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH=<checkout>/apps/server/dist/bin.mjs,
and T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT=19331 (19332 for the second side).
Use a fresh fixture and fresh desktop data for each commit.
After adding lima-sandbox with username user and an EMPTY Port field, stop the
40001 proxy, replace Port 40001 with Port 40002 in ssh_config, and start the
same proxy on 40002. Confirm terminal ssh -l user lima-sandbox works.
Run drive.mjs toggle twice to switch the saved environment off and back on.
"""
from pathlib import Path
import subprocess, sys
p=Path(sys.argv[1]).resolve(); p.mkdir(parents=True, exist_ok=False)
for directory in ['bin','remote-home']:(p/directory).mkdir()
for key in ['host-key','client-key']:
 subprocess.run(['ssh-keygen','-q','-t','ed25519','-N','','-f',str(p/key)],check=True)
(p/'authorized_keys').write_text((p/'client-key.pub').read_text())
(p/'sshd_config').write_text(f'''Port 22999
ListenAddress 127.0.0.1
HostKey {p}/host-key
PidFile {p}/sshd.pid
AuthorizedKeysFile {p}/authorized_keys
StrictModes no
PasswordAuthentication no
KbdInteractiveAuthentication no
UsePAM no
AllowUsers user
SetEnv HOME={p}/remote-home
LogLevel VERBOSE
''')
(p/'ssh_config').write_text(f'''Host lima-sandbox
 HostName 127.0.0.1
 Port 40001
 User alias-user
 IdentityFile {p}/client-key
 StrictHostKeyChecking no
 UserKnownHostsFile /dev/null
 LogLevel ERROR
''')
(p/'bin/ssh').write_text(f'#!/bin/sh\nexec /usr/bin/ssh -F {p}/ssh_config "$@"\n')
(p/'bin/ssh').chmod(0o755)
