import hashlib
import io
import json
import sys
import tarfile
from remote import ROOT, REMOTE, run, python

action=sys.argv[1]
if action=='transfer':
    archive=ROOT/'deployment.tar'
    if archive.exists():raise ValueError('R5_PRESERVE_ARCHIVE')
    with tarfile.open(archive,'w') as bundle:bundle.add(ROOT/'package',arcname='.')
    archive.chmod(0o600);data=archive.read_bytes();digest=hashlib.sha256(data).hexdigest()
    incoming='/home/si/fight-r5-20261101-r01.tar'
    run(['python3','-c','import sys\nfrom pathlib import Path\np=Path('+repr(incoming)+')\nassert not p.exists()\np.write_bytes(sys.stdin.buffer.read());p.chmod(0o600)'],payload=data)
    code='''import hashlib,io,os,tarfile
from pathlib import Path
raw=Path(INCOMING).read_bytes()
assert hashlib.sha256(raw).hexdigest()==DIGEST
root=Path(REMOTE)
assert not root.exists()
root.mkdir(mode=0o700)
with tarfile.open(fileobj=io.BytesIO(raw)) as bundle:bundle.extractall(root,filter='data')
root.chmod(0o700)
print('Verified source-only archive extracted.')
'''.replace('INCOMING',repr(incoming)).replace('DIGEST',repr(digest)).replace('REMOTE',repr(REMOTE))
    print(python(code,sudo=True).decode().strip())
    (ROOT/'archive.json').write_text(json.dumps(dict(sha256=digest,remote=REMOTE),indent=2)+'\n')
elif action in ('prepare','build','test','activate','verify'):
    raw=run(['python3',REMOTE+'/fight_r5_install.py',REMOTE,'icerti-ai2',action],sudo=True,timeout=420)
    (ROOT/(action+'.log')).write_bytes(raw);print(raw.decode()[-6000:])
else:
    raise ValueError('R5_ACTION_NOT_ALLOWED')
