#!/usr/bin/env python3
import hashlib
import json
import shlex
import subprocess
import sys
import tarfile
from pathlib import Path
root=Path(__file__).parent;workspace=root.parents[3];main=workspace/'zhctproject/store'
lane=sys.argv[1];assert lane in ('B','C')
wide=root.parent/'store-gift-wide-http-20261011/private-evidence'
runtime='/tmp/cdx-gift-date-'+lane+'-20261011'
private=root/'runtime-private';private.mkdir(mode=0o700,exist_ok=True)
archive=private/'source.tgz'
if not archive.exists():
    with archive.open('xb')as output:
        archive.chmod(0o600)
        subprocess.run(['tar','-C',str(main),'-czf','-','application'],stdout=output,check=True)
read_code=(root/'read-only.php').read_text().split('$ai=$connect(true);',1)[0]
files={name:(root/name).read_bytes() for name in ['http-index.php','http-run.php','worker.php','auth-private.php']}
files['context-private.php']=read_code.encode()
files['auth-seed.json']=json.dumps({'lease':json.loads((wide/('lease-'+lane+'.json')).read_text()),'oldWide':json.loads((wide/('fixture-journal-'+lane+'.json')).read_text())},ensure_ascii=False).encode()
lock={str(file.relative_to(main/'application')):hashlib.sha256(file.read_bytes()).hexdigest()for file in (main/'application').rglob('*.php')}
files['source-lock.json']=json.dumps(lock).encode()
import base64
payload=json.dumps({name:base64.b64encode(data).decode()for name,data in files.items()}).encode()
code='$root='+repr(runtime)+';if(file_exists($root))throw new RuntimeException("New runtime collision");mkdir($root,0700);mkdir($root."/source",0700);mkdir($root."/evidence",0700);foreach(json_decode(file_get_contents("php://stdin"),true)as $name=>$data){file_put_contents($root."/".$name,base64_decode($data));chmod($root."/".$name,0600);}echo "created isolated runtime\n";'
php='/usr/local/php7.3/bin/php'if lane=='B'else'/www/server/php/73/bin/php'
command=['docker','exec','-i','zhctapp_v2_0',php,'-r',code]if lane=='B'else['ssh','-S','/private/tmp/cdx-train-root-20261010.sock','-o','BatchMode=yes','root@121.43.241.161',php+' -r '+shlex.quote(code)]
subprocess.run(command,input=payload,check=True)
if lane=='B':
    subprocess.run(['docker','cp',str(archive),'zhctapp_v2_0:'+runtime+'/source.tgz'],check=True)
    subprocess.run(['docker','exec','zhctapp_v2_0','tar','-xzf',runtime+'/source.tgz','-C',runtime+'/source'],check=True)
else:
    subprocess.run(['scp','-q','-o','ControlPath=/private/tmp/cdx-train-root-20261010.sock','-o','BatchMode=yes',str(archive),'root@121.43.241.161:'+runtime+'/source.tgz'],check=True)
    subprocess.run(['ssh','-S','/private/tmp/cdx-train-root-20261010.sock','-o','BatchMode=yes','root@121.43.241.161','tar -xzf '+shlex.quote(runtime+'/source.tgz')+' -C '+shlex.quote(runtime+'/source')],check=True)
print(lane,runtime,'source snapshot prepared')
