#!/usr/bin/env python3
"""Run one complete program with the reviewed GNU Octave toolchain."""
import argparse,hashlib,json,os
from pathlib import Path
import subprocess,sys,tempfile
from xml.sax.saxutils import escape
root=Path(__file__).resolve().parents[1]
cfg=json.loads((root/'config/render.json').read_text());versions=json.loads((root/'VERSIONS.json').read_text())
cli=os.environ.get('OCTAVE','octave-cli')
version=subprocess.run([cli,'--version'],capture_output=True,text=True,check=True).stdout.splitlines()[0]
if not version.endswith('version '+cfg['octave']):sys.exit('Requires GNU Octave '+cfg['octave']+'; found '+version)
gnuplot=subprocess.run(['gnuplot','--version'],capture_output=True,text=True,check=True).stdout.strip()
if gnuplot!=cfg['gnuplot']:sys.exit('Requires '+cfg['gnuplot']+'; found '+gnuplot)
font=root/cfg['font_file']
if hashlib.sha256(font.read_bytes()).hexdigest()!=versions['font_sha256']:sys.exit('Local font checksum mismatch')
if sys.argv[1:]==['--version']:print('GNU Octave '+cfg['octave']+'; '+gnuplot);sys.exit(0)
if sys.argv[1:]==['--native-help']:sys.exit(subprocess.run([cli,'--help']).returncode)
p=argparse.ArgumentParser(description=__doc__);p.add_argument('source',type=Path);a=p.parse_args()
for folder in ['figures','generated']:(Path.cwd()/folder).mkdir(exist_ok=True)
with tempfile.TemporaryDirectory(prefix='octave-fonts-') as directory:
 conf=Path(directory)/'fonts.conf'
 conf.write_text('<fontconfig><dir>'+escape(str(font.parent))+'</dir><cachedir>'+escape(str(Path(directory)/'cache'))+'</cachedir></fontconfig>')
 env=dict(os.environ,FONTCONFIG_FILE=str(conf),PANGOCAIRO_BACKEND='fc',LC_ALL=cfg['locale'],LANG=cfg['locale'],GNUTERM='dumb',OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1',SOURCE_DATE_EPOCH='0')
 sys.exit(subprocess.run([cli,'--no-gui','--no-window-system','--norc','--no-history','--quiet',str(a.source)],env=env).returncode)
