| 1 | #!/usr/bin/env python3 |
| 2 | import json |
| 3 | import os |
| 4 | from pathlib import Path |
| 5 | import subprocess |
| 6 | import sys |
| 7 | |
| 8 | root = Path(__file__).resolve().parents[2] |
| 9 | sys.path.insert(0, str(root / 'tools')) |
| 10 | import manage as copyparty |
| 11 | |
| 12 | |
| 13 | data = json.load(sys.stdin) |
| 14 | cfg = Path(data['hostRoot']) / 'cfg' |
| 15 | service = Path(data['hostRoot']).name |
| 16 | variable = json.loads(subprocess.check_output( |
| 17 | ['nomad', 'var', 'get', '-out=json', 'nomad/jobs/' + service], |
| 18 | text=True, stderr=subprocess.DEVNULL, |
| 19 | )) |
| 20 | items = variable['Items'] |
| 21 | state_path = cfg / 'manager.json' |
| 22 | state = json.loads(state_path.read_text()) if state_path.exists() else {'accounts': [], 'grants': [], 'names': {}} |
| 23 | canonical_root = Path(os.environ.get('SNOWGLOBE_CLOVER_ROOT', str(Path(os.environ.get('SNOWGLOBE_ROOT', '/srv')) / 'clover'))) |
| 24 | origin = Path(state.get('root', str(canonical_root))) |
| 25 | if origin != canonical_root: |
| 26 | for grant in state['grants']: |
| 27 | grant['path'] = str(canonical_root / Path(grant['path']).relative_to(origin)) |
| 28 | state['root'] = str(canonical_root) |
| 29 | missing = ['file_api_' + account['id'].replace('-', '') for account in state['accounts'] |
| 30 | if 'file_api_' + account['id'].replace('-', '') not in items] |
| 31 | if missing and service != 'copyparty': |
| 32 | source = copyparty.runs.nomad('var/nomad/jobs/copyparty') |
| 33 | for key in missing: |
| 34 | if source is None or key not in source['Items']: |
| 35 | raise RuntimeError('Copyparty API credentials are missing from the source Nomad variables') |
| 36 | items[key] = source['Items'][key] |
| 37 | copyparty.runs.nomad('var/nomad/jobs/' + service + '?cas=' + str(variable['ModifyIndex']), 'PUT', |
| 38 | {'Namespace': 'default', 'Path': 'nomad/jobs/' + service, 'Items': items}) |
| 39 | elif missing: |
| 40 | raise RuntimeError('Copyparty API credentials are missing; restore its Nomad variables before starting it') |
| 41 | rendered = copyparty.configuration(cfg, state, items, Path(__file__).with_name('copyparty.conf')) |
| 42 | target = cfg / 'copyparty.conf' |
| 43 | if not target.exists() or target.read_bytes() != rendered: |
| 44 | copyparty.atomic(target, rendered, (data['uid'], data['uid'])) |
| 45 | os.chmod(target, 0o600) |
| 46 | os.chown(target, data['uid'], data['uid']) |
| 47 | |
| 48 | if service != 'copyparty': |
| 49 | public = Path(data['hostRoot']) / 'w/media/Software/Public/zig/0.0.0' |
| 50 | public.mkdir(parents=True, exist_ok=True) |
| 51 | fixture = public / 'zig-0.0.0.tar.xz' |
| 52 | fixture.write_bytes(b'Synthetic Zig mirror preview.\n') |
| 53 | for directory in [public, *public.parents]: |
| 54 | if directory == Path(data['hostRoot']): |
| 55 | break |
| 56 | os.chown(directory, data['uid'], data['uid']) |
| 57 | os.chown(fixture, data['uid'], data['uid']) |