import os, pathlib, subprocess, socket, json, signal, time
root = pathlib.Path(__file__).parent
children=[]
def run(*args, **kw): return subprocess.run(args, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kw)
def spawn(args, **kw):
    p=subprocess.Popen(args, **kw); children.append(p); return p
try:
    for name in ['host','identity']:
        run('ssh-keygen','-q','-t','ed25519','-N','','-f',str(root/name))
    (root/'authorized_keys').write_text((root/'identity.pub').read_text())
    (root/'confirm').write_text('#!/usr/bin/python3\nimport time, pathlib\npathlib.Path("'+str(root/'confirmation-requested')+'").write_text("pending")\ntime.sleep(3600)\n')
    (root/'confirm').chmod(0o755)
    sock=socket.socket(); sock.bind(('127.0.0.1',0)); port=sock.getsockname()[1]; sock.close()
    config=f'''Port {port}
ListenAddress 127.0.0.1
HostKey {root}/host
PidFile {root}/sshd.pid
AuthorizedKeysFile {root}/authorized_keys
StrictModes no
PasswordAuthentication no
KbdInteractiveAuthentication no
UsePAM no
LogLevel VERBOSE
'''
    (root/'sshd_config').write_text(config)
    sshd=spawn(['/usr/sbin/sshd','-D','-e','-f',str(root/'sshd_config')],stderr=open(root/'sshd.log','w'))
    agentenv=dict(os.environ,DISPLAY=':99',SSH_ASKPASS=str(root/'confirm'),SSH_ASKPASS_REQUIRE='force')
    agent=spawn(['ssh-agent','-D','-a',str(root/'agent.sock')],env=agentenv,stdout=open(root/'agent.log','w'),stderr=subprocess.STDOUT)
    for _ in range(100):
        if (root/'agent.sock').exists(): break
        time.sleep(.05)
    run('ssh-add','-c',str(root/'identity'),env=dict(agentenv,SSH_AUTH_SOCK=str(root/'agent.sock')))
    (root/'ssh_config').write_text(f'''Host authorization-fixture
 HostName 127.0.0.1
 Port {port}
 User user
 IdentityAgent {root}/agent.sock
 IdentityFile {root}/identity.pub
 IdentitiesOnly yes
 StrictHostKeyChecking no
 UserKnownHostsFile /dev/null
 LogLevel ERROR
''')
    run('git','init','--bare','--initial-branch=main',str(root/'remote.git'))
    run('git','init','--initial-branch=main',str(root/'seed'))
    (root/'seed/README.md').write_text('SSH authorization reproduction\n')
    run('git','-C',str(root/'seed'),'add','.')
    run('git','-C',str(root/'seed'),'-c','user.name=Scenario','-c','user.email=scenario@example.invalid','commit','-m','Initial commit')
    run('git','-C',str(root/'seed'),'push',str(root/'remote.git'),'main')
    (root/'env.json').write_text(json.dumps({'remote':f'authorization-fixture:{root}/remote.git','local':str(root/'remote.git'),'ssh':f'ssh -F {root}/ssh_config','agentPid':agent.pid}))
    print('SSH confirmation fixture ready',flush=True)
    while True: time.sleep(1)
except KeyboardInterrupt: pass
finally:
    for p in reversed(children):
        p.terminate()
    for p in children:
        try: p.wait(timeout=5)
        except subprocess.TimeoutExpired: p.kill(); p.wait()
