"""Create the synthetic SSH fixture. Usage: python3 seed-local-ssh.py SCRATCH.
Requires ssh-keygen and sshd. Start sshd with the generated sshd_config.
Run a local HTTP server on 19468, and serve the newer AppImage feed on 19369.
This deliberately stands in for remote server discovery; the desktop opens real SSH forwards.
No agent, account, or real user database is used. Remove the generated SSH config after use.
"""
from pathlib import Path
import getpass
import subprocess
import sys
p=Path(sys.argv[1]).resolve()
p.mkdir(parents=True, exist_ok=True)
for key in ['host_key', 'client_key']:
    subprocess.run(['ssh-keygen','-q','-t','ed25519','-N','','-f',str(p/key)],check=True)
(p/'remote-command.sh').write_text('#!/bin/sh\ncat >/dev/null\nprintf \'{"remotePort":19468,"serverKind":"external"}\\n\'\n')
(p/'remote-command.sh').chmod(0o755)
(p/'authorized_keys').write_text('command="'+str(p/'remote-command.sh')+'" '+(p/'client_key.pub').read_text())
(p/'sshd_config').write_text(f'''Port 19268
ListenAddress 127.0.0.1
HostKey {p}/host_key
PidFile {p}/sshd.pid
AuthorizedKeysFile {p}/authorized_keys
StrictModes no
PasswordAuthentication no
UsePAM no
AllowTcpForwarding yes
''')
c=Path.home()/'.ssh/config'
assert not c.exists(), 'Use an isolated account with no existing SSH config.'
c.write_text(f'''Host ssh-proof-local
 HostName 127.0.0.1
 Port 19268
 User {getpass.getuser()}
 IdentityFile {p}/client_key
 StrictHostKeyChecking no
 UserKnownHostsFile /dev/null
''')
c.chmod(0o600)
