from pathlib import Path
import subprocess, shutil, os, shlex
r=Path(__file__).resolve().parent
for name in ['host-key','client-key']:
    if not (r/name).exists():
        subprocess.run(['ssh-keygen','-q','-t','ed25519','-N','','-f',str(r/name)],check=True)
node_dir=str(Path(shutil.which('node')).resolve().parent)
(r/'remote-shell').write_text('#!/bin/sh\nexport HOME="$(cat '+shlex.quote(str(r/'remote-home'))+')"\nexport PATH='+shlex.quote(node_dir+':/usr/local/bin:/usr/bin:/bin')+'\nexport T3CODE_ENVIRONMENT_LABEL="Shared SSH server"\nexec /bin/sh -c "$SSH_ORIGINAL_COMMAND"\n')
(r/'remote-shell').chmod(0o755)
(r/'bin').mkdir(exist_ok=True)
(r/'bin/ssh').write_text('#!/bin/sh\nexec /usr/bin/ssh -i '+shlex.quote(str(r/'client-key'))+' -o UserKnownHostsFile='+shlex.quote(str(r/'known-hosts'))+' -o StrictHostKeyChecking=accept-new "$@"\n')
(r/'bin/ssh').chmod(0o755)
(r/'sshd.conf').write_text(f'''Port 22418
ListenAddress 127.0.0.1
HostKey {r}/host-key
PidFile {r}/sshd.pid
AuthorizedKeysFile {r}/client-key.pub
StrictModes no
PasswordAuthentication no
KbdInteractiveAuthentication no
UsePAM no
AllowUsers {os.getlogin() if os.isatty(0) else __import__('getpass').getuser()}
AllowTcpForwarding yes
ForceCommand {r}/remote-shell
LogLevel ERROR
''')
print('SSH configuration ready; start sshd -D -e -f '+str(r/'sshd.conf'))
