#!/usr/bin/env python3
"""Synthetic proof fixture. Usage: python3 setup-forges.py /path/to/empty/fixture
Requires Docker, OpenSSL, and gitea.test resolving to 127.0.0.1. Trust tls/cert.pem
in the test browser and pass it as NODE_EXTRA_CA_CERTS. Install tea >=0.16 and
create only the default-port login using default/token, with XDG_CONFIG_HOME
pointing at fixture/tea-config. No credential for port 8443 is configured.
The scenario resets both comment lists before each side. Never use production data.
"""
from pathlib import Path
import base64, json, secrets, ssl, subprocess, sys, time, urllib.request
p = Path(sys.argv[1]).resolve()
p.mkdir(parents=True, exist_ok=True)
(p/'tls').mkdir(exist_ok=True)
subprocess.run(['openssl','req','-x509','-newkey','rsa:2048','-nodes','-keyout',str(p/'tls/key.pem'),'-out',str(p/'tls/cert.pem'),'-days','2','-subj','/CN=gitea.test','-addext','subjectAltName=DNS:gitea.test'],check=True)
(p/'tls/key.pem').chmod(0o644)
pw = secrets.token_urlsafe(24)
ctx = ssl._create_unverified_context()
for side, port in [('default',443),('ported',8443)]:
 d=p/side
 d.mkdir(exist_ok=True)
 origin=f'https://gitea.test{":8443" if port==8443 else ""}'
 (d/'app.ini').write_text(f'''APP_NAME = Port isolation forge — {side}
RUN_MODE = prod
RUN_USER = git
[database]
DB_TYPE = sqlite3
PATH = /data/gitea/gitea.db
[server]
PROTOCOL = https
DOMAIN = gitea.test
ROOT_URL = {origin}/
HTTP_PORT = 3000
CERT_FILE = /tls/cert.pem
KEY_FILE = /tls/key.pem
DISABLE_SSH = true
[security]
INSTALL_LOCK = true
[service]
DISABLE_REGISTRATION = true
REQUIRE_SIGNIN_VIEW = false
''')
 name=f'proof38010-{side}'
 result=subprocess.run(['docker','run','-d','--name',name,'-p',f'127.0.0.1:{port}:3000','-v',f'{d}/app.ini:/data/gitea/conf/app.ini','-v',f'{p}/tls:/tls:ro','gitea/gitea:1.25.1'],check=True,capture_output=True,text=True)
 (d/'container-id').write_text(result.stdout.strip())
 for attempt in range(60):
  try:
   urllib.request.urlopen(origin+'/api/v1/version',context=ctx).close()
   break
  except Exception:
   time.sleep(1)
 else: raise RuntimeError('Gitea did not start')
 subprocess.run(['docker','exec','--user','git',name,'gitea','admin','user','create','--username','acme','--password',pw,'--email','proof@example.invalid','--admin','--must-change-password=false'],check=True)
 def req(path,data):
  headers={'Authorization':'Basic '+base64.b64encode(f'acme:{pw}'.encode()).decode(),'Content-Type':'application/json'}
  return json.load(urllib.request.urlopen(urllib.request.Request(origin+'/api/v1/'+path,data=json.dumps(data).encode(),headers=headers),context=ctx))
 (d/'token').write_text(req('users/acme/tokens',{'name':'port-proof','scopes':['all']})['sha1'])
 req('user/repos',{'name':'web','auto_init':True,'private':False})
 for n in range(1,4):
  req('repos/acme/web/issues',{'title':('DEFAULT PORT — must not be accessed' if side=='default' else 'PORT 8443 — requested issue') if n==3 else f'Seed issue {n}','body':f'This issue belongs to the {side} server. Synthetic port isolation fixture.'})
print('Both Gitea instances seeded. Tokens stay local; upload this script, never the fixture directory.')
