#!/usr/bin/env python3
# Copyright 2026 Johannes Schauer Marin Rodrigues <josch@mister-muffin.de>
# SPDX-License-Identifier: GPL-3.0-or-later

from pathlib import Path
import subprocess

# we don't use xml.etree.ElementTree because it does not preserve comments
import lxml.etree as ET
import os, sys


def main():
    for p in sorted(Path("./fonts/ttf/").glob("JetBrainsMono-*.ttf")):
        print(p, file=sys.stderr)
        ttxp = p.with_suffix(".ttx")
        if ttxp.exists():
            ttxp.unlink()
        subprocess.check_call(["ttx", p])
        document = ET.parse(ttxp)
        root = document.getroot()
        root.remove(root.find("GPOS"))
        root.remove(root.find("GSUB"))
        for ppath, ename in [
            ("GlyphOrder", "GlyphID"),
            ("glyf", "TTGlyph"),
            ("hmtx", "mtx"),
            ("post/extraNames", "psName"),
        ]:
            parent = root.find(ppath)
            for child in parent.findall(ename):
                if child.attrib["name"].endswith(".liga"):
                    parent.remove(child)
        for el in root.findall("name/namerecord"):
            if "trademark" in el.text:
                continue
            el.text = el.text.replace("JetBrains Mono", "JetBrains Mono NL")
            el.text = el.text.replace("JetBrainsMono", "JetBrainsMonoNL")
        NLttfp = p.with_stem(p.stem.replace("JetBrainsMono", "JetBrainsMonoNL"))
        if NLttfp.exists():
            NLttfp.unlink()
        NLttxp = NLttfp.with_suffix(".ttx")
        document.write(NLttxp, xml_declaration=True, encoding="UTF-8", standalone=False)
        sde = os.environ.get("SOURCE_DATE_EPOCH")
        if sde is not None:
            os.utime(NLttxp, (int(sde), int(sde)))
        subprocess.check_call(["ttx", NLttxp])
        NLttxp.unlink()
        ttxp.unlink()


if __name__ == "__main__":
    main()
