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

repo=Path('/workspace/contextra-analytics-runtime-lifecycle-refactor')
archive=ROOT/'test-support-r02.tar'
with tarfile.open(archive,'w') as bundle:
    for name in ('fight_r5_install.py','fight_r5_package.py'):
        bundle.add(repo/'tools/icerti_offline'/name,arcname=name)
    for source in (repo/'tests').rglob('*.py'):
        bundle.add(source,arcname=str(Path('tests')/source.relative_to(repo/'tests')))
raw=archive.read_bytes();digest=hashlib.sha256(raw).hexdigest()
incoming='/home/si/fight-r5-test-support-r02.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=raw)
code='''import hashlib,io,json,shutil,tarfile
from pathlib import Path
root=Path(ROOT)
assert not (root/'transition.json').exists()
raw=Path(INCOMING).read_bytes();assert hashlib.sha256(raw).hexdigest()==DIGEST
backup=root/'support-r01-backup';backup.mkdir(mode=0o700)
for name in ('fight_r5_install.py','fight_r5_package.py'):shutil.copy2(root/name,backup/name)
with tarfile.open(fileobj=io.BytesIO(raw)) as bundle:bundle.extractall(root,filter='data')
manifest=json.loads((root/'manifest.json').read_text())
assert all(hashlib.sha256((root/'payload'/name).read_bytes()).hexdigest()==value for name,value in manifest['after'].items())
(root/'support-r02.json').write_text(json.dumps(dict(archive_sha256=DIGEST,payload_unchanged=True),indent=2))
print('Test fixtures and logging updated; R5 payload/image unchanged.')
'''.replace('ROOT',repr(REMOTE),1).replace('INCOMING',repr(incoming)).replace('DIGEST',repr(digest))
print(python(code,sudo=True).decode().strip())
