plugins/tools/allow-giedi-nether-pearl.py
unimatrixgit 426c6729c3
All checks were successful
Giedi Nether Ender Pearl Operations Build / giedi-nether-pearl (push) Successful in 5s
DuneRealms Plugin CI / plugins (push) Successful in 2m59s
Pin the actual installed Towny filename
2026-12-02 11:59:30 +01:00

130 lines
5.2 KiB
Python

"""Allow Ender Pearls in Giedi Prime Nether wilderness through Towny's command."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import stat
import subprocess
import time
ROOT = Path('/opt/dunerealms/servers/giedi_prime')
UNIT = 'dune-giedi_prime.service'
WORLD = 'giedi_prime_nether'
TOWNY_SHA = 'c8d7d59984eaf2606fce4192e860f7f969f3384e5a51b26b97225efbbe747c70'
WORLD_SHA = '7f335ddab1891f774f966f896b49127c2f1fe0bbfdecf3b8e3eb41933ea5a02f'
CONFIG_SHA = '7440231da22718cba4c402d8b07594484aacd840b3c01ab81c4d2a6f1fcfac1f'
IGNORE = 'unclaimedZoneIgnoreIds'
PEARL = 'ENDER_PEARL'
def sha(path):
if not path.is_file() or path.absolute() != path.resolve(strict=True):
raise ValueError(f'Expected a regular canonical file: {path}')
return hashlib.sha256(path.read_bytes()).hexdigest()
def fields(text):
result = {}
for line in text.splitlines():
if not line.strip() or line.lstrip().startswith('#'):
continue
key, separator, value = line.partition('=')
if not separator or not key or key in result:
raise ValueError('Unexpected Towny world file syntax')
result[key] = value
return result
def materials(data):
names = data.get(IGNORE, '').split(',')
if any(not re.fullmatch(r'[A-Z0-9_]+', name) for name in names) or len(set(names)) != len(names):
raise ValueError('Expected Towny to have saved a canonical list of distinct materials')
return names
def command(before):
if before.get('usingTowny') != 'true' or before.get('unclaimedZoneItemUse') != 'false':
raise ValueError('Expected the current Nether wilderness protection policy')
old = materials(before)
if PEARL in old:
raise ValueError('The Nether exception is already installed')
return f'townyworld {WORLD} set wildignore ' + ' '.join([*old, PEARL])
def verify(before, after):
if set(materials(after)) != {*materials(before), PEARL}:
raise ValueError('Towny did not save exactly the Ender Pearl exception')
if {key: value for key, value in before.items() if key != IGNORE} != {
key: value for key, value in after.items() if key != IGNORE
}:
raise ValueError('Unexpected change to another Towny world field')
def send(fifo, line):
payload = (line + '\n').encode('ascii')
fd = os.open(fifo, os.O_WRONLY | os.O_NONBLOCK | os.O_NOFOLLOW)
try:
if not stat.S_ISFIFO(os.fstat(fd).st_mode) or len(payload) > os.fpathconf(fd, 'PC_PIPE_BUF'):
raise ValueError('Expected one atomic write to the native console FIFO')
if os.write(fd, payload) != len(payload):
raise OSError('Incomplete console write')
finally:
os.close(fd)
def service(*args):
return subprocess.run(['systemctl', *args], text=True, capture_output=True, check=True).stdout.strip()
def run(apply):
if service('is-active', UNIT) != 'active' or service('show', UNIT, '--property=WorkingDirectory', '--value') != str(ROOT):
raise ValueError('Expected the active Giedi Prime server')
plugins = ROOT / 'plugins'
towny = plugins / 'Towny-0.103.2.0.jar'
config = plugins / 'Towny/settings/config.yml'
worlds = plugins / 'Towny/data/worlds'
target = worlds / f'{WORLD}.txt'
if sha(towny) != TOWNY_SHA or sha(config) != CONFIG_SHA or sha(target) != WORLD_SHA:
raise ValueError('Towny, its configuration, or the target world differs from preflight')
before = fields(target.read_text())
operation = command(before)
result = {'unit': UNIT, 'world': WORLD, 'material': PEARL, 'beforeSha256': WORLD_SHA, 'status': 'planned'}
if not apply:
return result
siblings = {path.name: sha(path) for path in worlds.glob('*.txt') if path != target}
if sha(towny) != TOWNY_SHA or sha(config) != CONFIG_SHA or sha(target) != WORLD_SHA:
raise ValueError('Towny settings changed before the console call')
send(ROOT / 'console.fifo', operation)
for _ in range(40):
time.sleep(.25)
try:
observed = sha(target)
after = fields(target.read_text())
except (FileNotFoundError, ValueError):
continue
if observed != WORLD_SHA and PEARL in after.get(IGNORE, '').split(','):
verify(before, after)
if sha(towny) != TOWNY_SHA or sha(config) != CONFIG_SHA or siblings != {
path.name: sha(path) for path in worlds.glob('*.txt') if path != target
}:
raise ValueError('Unexpected change to another Towny file')
return {**result, 'status': 'persisted', 'afterSha256': observed, 'otherWorldsVerified': len(siblings)}
raise RuntimeError('Towny save was not confirmed. Inspect native console before retrying.')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--apply', action='store_true')
options = parser.parse_args()
if options.apply:
import fcntl
with Path('/run/lock/dunerealms-giedi-nether-pearl.lock').open('a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
report = run(True)
else:
report = run(False)
print(json.dumps(report, indent=2))