import hashlib
import json
import os
from pathlib import Path
import shlex
import shutil
import stat
import subprocess
import sys
import tarfile

root=Path(__file__).parent
repo=Path('/workspace/contextra-analytics-runtime-lifecycle-refactor')
remote='/storage/contextra/maintenance/event-pin-20261023-r01'
ssh=['ssh','-T','-p','1022','-i','/root/.ssh/ltb1021_contextra_icerti2_si_ed25519','-o','BatchMode=yes','-o','StrictHostKeyChecking=yes','-o','UserKnownHostsFile=/root/.ssh/contextra_icerti2_known_hosts','si@58.233.207.31']
secret=Path('/data/contextra-maintenance/secrets/icerti-ai2/sudo.password')
def run(command, *, sudo=False, timeout=30):
    if sudo:
        s=secret.stat()
        assert s.st_uid==0 and stat.S_IMODE(s.st_mode)==0o600 and not secret.is_symlink()
    p=subprocess.run(ssh+[("sudo -S -p '' "+command) if sudo else command],
                     input=(secret.read_bytes().rstrip(b'\n')+b'\n') if sudo else None,
                     capture_output=True,timeout=timeout)
    if p.returncode:raise RuntimeError(p.stderr.decode(errors='replace')[-1000:]+p.stdout.decode(errors='replace')[-1000:])
    return p.stdout

action=sys.argv[1]
if action=='package':
    package=root/'package'
    if (root/'deployment.tar').exists():raise SystemExit('Preserve packaged snapshot')
    package.mkdir(mode=0o700,exist_ok=True)
    after={}
    for name in ('app/event_capture.py','app/protected_packet_cache.py'):
        dest=package/'payload'/name;dest.parent.mkdir(parents=True,exist_ok=True)
        shutil.copyfile(repo/name,dest);dest.chmod(0o644)
        after[name]=hashlib.sha256(dest.read_bytes()).hexdigest()
    rows=run("docker inspect contextra-ai2-analytics-1 contextra-ai2-ai-control-sidecar-1 contextra-ai2-ai-gateway-1 contextra-ai2-redis-1 contextra-ai2-postgresql-1 --format '{{index .Config.Labels \"com.docker.compose.service\"}} {{.Image}}'").decode().splitlines()
    images=dict(r.split() for r in rows)
    assert images['analytics']=='sha256:e5756f7bef496b0007b186a0f866a67d3e6723102dc053cd9d1dc54838f39a88'
    before={'app/event_capture.py':'61e7c51a2fd2ba7145018f5cfd4adcbe0452ad97b0194cb4049ed4c0590a9e3c',
            'app/event_artifact_store.py':'2ae2d66766ddc3bc407eda47a8c99b5252f11d3b8e266b0b25fb1520f3111bd1',
            'app/event_artifact_contract.py':'f61e380d59093f71aa6bd13f75e5ce21c89e3e938df8b23105b96d40510696d1'}
    (package/'manifest.json').write_text(json.dumps(dict(server='icerti-ai2',images=images,before=before,after=after),indent=2))
    for name in ('event_pin_install.py','artifact_install.py','trace_install.py'):
        shutil.copyfile(repo/'tools/icerti_offline'/name,package/name)
    tests=package/'tests';tests.mkdir(exist_ok=True)
    for name in ('test_protected_packet_cache.py','test_capture_trial.py','test_event_artifact.py'):
        shutil.copyfile(repo/'tests'/name,tests/name)
    archive=root/'deployment.tar'
    with tarfile.open(archive,'w') as tar:tar.add(package,arcname='event-pin-20261023-r01')
    p=subprocess.run(ssh+['umask 077; test ! -e /home/si/event-pin-20261023-r01.tar && dd of=/home/si/event-pin-20261023-r01.tar status=none'],input=archive.read_bytes(),capture_output=True,timeout=30)
    if p.returncode:raise RuntimeError('Package transfer failed')
    command="python3 -c "+shlex.quote("import pathlib,tarfile; p=pathlib.Path('"+remote+"'); assert not p.exists(); tarfile.open('/home/si/event-pin-20261023-r01.tar').extractall('/storage/contextra/maintenance',filter='data'); p.chmod(0o700)")
    print(run(command,sudo=True).decode())
    print(json.dumps(dict(after=after,images=images)))
elif action in ('prepare','build','activate','finish_activation','verify'):
    output=run('python3 '+remote+'/event_pin_install.py '+remote+' icerti-ai2 '+action,sudo=True,timeout=420)
    (root/(action+'.log')).write_bytes(output)
    print(output.decode()[-8000:])
else:raise SystemExit('Unsupported action')
