#!/usr/bin/env python3
"""Prepare an isolated T3 home's registry-version reproduction, with its server stopped.
Usage: registry-state.py T3_HOME REGISTRY_JSON OLD_ARCHIVE SAVED_CURRENT_DIR older|advance
Providers are added through Settings before this script is used.
"""
import json, pathlib, shutil, sys, tarfile
home, source, archive, saved, phase = map(pathlib.Path, sys.argv[1:])
phase = str(phase)
registry = json.loads(source.read_text())
agent = next(a for a in registry['agents'] if a['id'] == 'devin')
if phase == 'older':
    current = home / 'tools/devin/3000.12.43'
    if current.exists():
        shutil.move(str(current), str(saved))
    target = home / 'tools/devin/3000.12.42/linux-x86_64'
    target.mkdir(parents=True, exist_ok=True)
    with tarfile.open(archive) as bundle:
        bundle.extractall(target, filter='data')
    agent['version'] = '3000.12.42'
    for binary in agent['distribution']['binary'].values():
        binary['archive'] = binary['archive'].replace('3000.12.43', '3000.12.42')
cache = home / 'caches/acp-registry/registry.json'
cache.parent.mkdir(parents=True, exist_ok=True)
cache.write_text(json.dumps(registry))
print('Registry version:', agent['version'])
print('Installed versions:', ', '.join(p.name for p in (home / 'tools/devin').iterdir()))
