1#!/usr/bin/env python3
2import json
3import os
4from pathlib import Path
5import subprocess
6import sys
7
8root = Path(__file__).resolve().parents[2]
9sys.path.insert(0, str(root / 'tools'))
10import manage as copyparty
11
12
13data = json.load(sys.stdin)
14cfg = Path(data['hostRoot']) / 'cfg'
15service = Path(data['hostRoot']).name
16variable = json.loads(subprocess.check_output(
17 ['nomad', 'var', 'get', '-out=json', 'nomad/jobs/' + service],
18 text=True, stderr=subprocess.DEVNULL,
19))
20items = variable['Items']
21state_path = cfg / 'manager.json'
22state = json.loads(state_path.read_text()) if state_path.exists() else {'accounts': [], 'grants': [], 'names': {}}
23canonical_root = Path(os.environ.get('SNOWGLOBE_CLOVER_ROOT', str(Path(os.environ.get('SNOWGLOBE_ROOT', '/srv')) / 'clover')))
24origin = Path(state.get('root', str(canonical_root)))
25if origin != canonical_root:
26 for grant in state['grants']:
27 grant['path'] = str(canonical_root / Path(grant['path']).relative_to(origin))
28state['root'] = str(canonical_root)
29missing = ['file_api_' + account['id'].replace('-', '') for account in state['accounts']
30 if 'file_api_' + account['id'].replace('-', '') not in items]
31if 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})
39elif missing:
40 raise RuntimeError('Copyparty API credentials are missing; restore its Nomad variables before starting it')
41rendered = copyparty.configuration(cfg, state, items, Path(__file__).with_name('copyparty.conf'))
42target = cfg / 'copyparty.conf'
43if not target.exists() or target.read_bytes() != rendered:
44 copyparty.atomic(target, rendered, (data['uid'], data['uid']))
45os.chmod(target, 0o600)
46os.chown(target, data['uid'], data['uid'])
47
48if 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'])