Files
metin2-client/tools/server/ava2-followup/install.py
T

86 lines
4.4 KiB
Python

#!/usr/bin/env python3
"""Compile in isolation; --apply backs up and installs only travel/sash objects and the missing quest helper."""
import argparse
import hashlib
import json
import shutil
import subprocess
from pathlib import Path
ROOT=Path(__file__).resolve().parent
def gbk(text):
raw=text.encode('gbk')
if b'\\' in raw:raise ValueError('GBK backslash byte is unsafe for qc')
return raw
def prepare(quest,stage):
stage.mkdir(parents=True,exist_ok=False)
functions=(quest/'quest_functions').read_bytes()
if b'pc.open_sash' not in functions.splitlines():functions=functions.rstrip()+b'\npc.open_sash\n'
(stage/'quest_functions').write_bytes(functions)
for name,source in [('ava2_travel',ROOT/'ava2_travel.quest'),('sash',ROOT.parent/'sash/sash.quest')]:
(stage/(name+'.quest')).write_bytes(gbk(source.read_text()))
result=subprocess.run([str((quest/'qc').resolve()),name+'.quest'],cwd=stage,capture_output=True)
(stage/(name+'.qc.log')).write_bytes(result.stdout+result.stderr)
if result.returncode or not (stage/'object/state'/name).is_file():
raise RuntimeError('qc failed for '+name+'; inspect '+str(stage/(name+'.qc.log')))
return stage
def install(quest,stage,backup):
backup.mkdir(parents=True,exist_ok=False)
files={Path('quest_functions'):(stage/'quest_functions').read_bytes()}
listing=(quest/'locale_list').read_bytes()
for name in (b'ava2_travel.quest',b'sash.quest'):
if name not in listing.splitlines():listing=listing.rstrip()+b'\n'+name+b'\n'
files[Path(name.decode())]=(stage/name.decode()).read_bytes()
files[Path('locale_list')]=listing
for path in (stage/'object').rglob('*'):
if path.is_file():files[Path('object')/path.relative_to(stage/'object')]=path.read_bytes()
library=(quest/'questlib.lua').read_bytes()
marker=b'-- PORT AVA2 missing quest helper'
if marker not in library:
files[Path('questlib.lua')]=library.rstrip()+b'\n'+marker+b'\n'+(ROOT/'quest_compat.lua').read_bytes()+b'\n'
manifest=[]
# Refuse a symlink out of the requested quest tree (sbtest must not modify live objects).
for relative,data in files.items():
target=quest/relative
if quest.resolve() not in target.resolve().parents:raise ValueError('target escapes quest tree: '+str(target))
existed=target.exists()
if existed:
old=backup/relative;old.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(target,old)
manifest.append({'path':str(relative),'existed':existed,'installed_sha256':hashlib.sha256(data).hexdigest()})
(backup/'manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
for relative,data in files.items():
target=quest/relative;target.parent.mkdir(parents=True,exist_ok=True)
temporary=target.with_name(target.name+'.ava2-new');temporary.write_bytes(data);temporary.replace(target)
return manifest
def rollback(quest,backup):
manifest=json.loads((backup/'manifest.json').read_text())
for row in manifest:
path=quest/row['path']
if path.exists() and hashlib.sha256(path.read_bytes()).hexdigest()!=row['installed_sha256']:
raise ValueError('changed since installation; refusing to overwrite '+str(path))
for row in manifest:
path=quest/row['path']
if row['existed']:shutil.copy2(backup/row['path'],path)
elif path.is_file():path.unlink()
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--server',type=Path,default=Path('/usr/metin2/server/sbtest'))
parser.add_argument('--locale',default='newcibn')
parser.add_argument('--work',type=Path,required=True)
parser.add_argument('--apply',action='store_true')
parser.add_argument('--rollback',action='store_true')
args=parser.parse_args();quest=args.server/'share/locale'/args.locale/'quest'
if args.apply and args.server.resolve() not in quest.resolve().parents:
raise ValueError('quest tree points outside --server; isolate sbtest first')
if args.rollback:rollback(quest,args.work/'backup');print('Restored; reload quests or restart target cores.')
else:
prepare(quest,args.work/'compiled');print('Compiled:',args.work/'compiled')
if args.apply:
install(quest,args.work/'compiled',args.work/'backup')
print('Installed with backup:',args.work/'backup','; reload/restart target cores to activate.')