from pathlib import Path
import subprocess,os
p=Path(os.environ['PROOF_ROOT']).resolve()
for d in ['remote-account','client-bin','shasum-bin','client-home']: (p/d).mkdir(exist_ok=True)
subprocess.run(['ssh-keygen','-q','-t','ed25519','-N','','-f',str(p/'key')],check=True)
(p/'authorized_keys').write_text((p/'key.pub').read_text())
(p/'mode').write_text('base-sha256sum')
for f in Path('/usr/bin').iterdir():
 if f.name!='sha256sum' and f.is_file():
  try: (p/'shasum-bin'/f.name).symlink_to(f)
  except FileExistsError: pass
shell=p/'bash'
shell.write_text((Path(__file__).parent/'remote-login-shell.sh').read_text().replace('ROOT=PROOF_ROOT', 'ROOT='+str(p)))
shell.chmod(0o755)
subprocess.run(['sudo','-n','useradd','-M','-d',str(p/'remote-account'),'-s',str(p/'bash'),'t3proof37150'],check=True)
subprocess.run(['sudo','-n','usermod','-p','*','t3proof37150'],check=True)
subprocess.run(['sudo','-n','chown','-R','t3proof37150:t3proof37150',str(p/'remote-account')],check=True)
(p/'sshd_config').write_text(f'''Port 22471
ListenAddress 127.0.0.1
HostKey /etc/ssh/ssh_host_ed25519_key
PidFile {p}/sshd.pid
AuthorizedKeysFile {p}/authorized_keys
StrictModes no
PasswordAuthentication no
KbdInteractiveAuthentication no
UsePAM no
AllowUsers t3proof37150
AllowTcpForwarding yes
''')
(p/'client-bin'/'ssh').write_text(f'#!/bin/sh\nexec /usr/bin/ssh -i {p}/key -o IdentitiesOnly=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile={p}/known_hosts "$@"\n')
(p/'client-bin'/'ssh').chmod(0o755)

(p/'tamper-bin').mkdir(exist_ok=True)
for name in ['curl','tar']:
 f=p/'tamper-bin'/name;f.write_text((Path(__file__).parent/('remote-'+name+'.sh')).read_text());f.chmod(0o755)
