import base64
import hashlib
import json
import os
from pathlib import Path
import subprocess
import urllib.request

os.umask(0o077)
HERE = Path(__file__).parent
REPO = Path('/workspace/contextra-analytics-runtime-lifecycle-refactor')
def command(args, timeout=10):
    return subprocess.run(args, check=True, capture_output=True, text=True, timeout=timeout).stdout
def save(name, value):
    with (HERE / name).open('x') as f:
        json.dump(value, f, indent=2)

before = {'head': command(['git', '-C', str(REPO), 'rev-parse', 'HEAD']).strip(),
          'neighbor': json.loads(command(['ip', '-j', 'neigh', 'show', '192.168.50.101'])),
          'route': json.loads(command(['ip', '-j', 'route', 'get', '192.168.50.101']))}
actual = json.loads(command(['docker', 'inspect', 'contextra-analytics-1']))[0]
env = dict(x.split('=', 1) for x in actual['Config']['Env'])
before['analytics'] = {'id': actual['Id'], 'image': actual['Image'], 'pid': actual['State']['Pid'],
                       'artifact': env.get('CONTEXTRA_EVENT_ARTIFACT_ENABLED'),
                       'http': env.get('CONTEXTRA_ARTIFACT_HTTP_ENABLED')}
with urllib.request.urlopen('http://127.0.0.1:35000/api/v1/streams', timeout=5) as r:
    streams = json.load(r)['streams']
before['streams'] = [{k: s.get(k) for k in ('stream_id', 'source_id', 'state')} for s in streams]
save('before.json', before)
assert before['route'][0]['dev'] == 'enp6s18'
assert before['route'][0]['prefsrc'] == '192.168.50.221'
for n in before['neighbor']:
    if 'PERMANENT' in n.get('state', []):
        assert n.get('lladdr') == 'bc:24:11:8a:6e:f4', 'EXISTING_STATIC_NEIGHBOR_CONFLICT'
if not any(n.get('lladdr') == 'bc:24:11:8a:6e:f4' and 'PERMANENT' in n.get('state', []) for n in before['neighbor']):
    save('neighbor-call.json', {'action': 'single_neighbor_replace', 'persistent_config': False})
    command(['ip', 'neigh', 'replace', '192.168.50.101', 'lladdr', 'bc:24:11:8a:6e:f4',
             'nud', 'permanent', 'dev', 'enp6s18'])
scan = command(['ssh-keyscan', '-T', '4', '-p', '2222', '-t', 'ed25519', '192.168.50.101'])
lines = [s for s in scan.splitlines() if s and not s.startswith('#')]
assert len(lines) == 1
fp = 'SHA256:' + base64.b64encode(hashlib.sha256(base64.b64decode(lines[0].split()[2])).digest()).decode().rstrip('=')
assert fp == 'SHA256:waBLTrBIy6sW2rl6Lur5UsLYsxzt6r1UANRqqofvI8c', 'HOST_KEY_MISMATCH'
known = Path('/root/.ssh/contextra_101_known_hosts')
if known.exists():
    assert known.read_text() == lines[0] + '\n'
else:
    with known.open('x') as f:
        f.write(lines[0] + '\n')
    known.chmod(0o600)
save('network.json', {'neighbor': json.loads(command(['ip', '-j', 'neigh', 'show', '192.168.50.101'])),
                      'ssh_fingerprint': fp, 'persistent_config': False})
print('NEIGHBOR_PINNED_HOST_KEY_VERIFIED')
