"""Update bundled xml files

We try to match the behaviour of the python toolchain, so we want to ship the
same data files as are currently bundled in glyphsLib. This script copies those
files out of the currently active version of glyphsLib.

Usage:
    python data/update.py
"""

import glyphsLib
from importlib import resources
import os
import shutil

def script_dir():
    return os.path.dirname(os.path.abspath(__file__))

def get_data_file(filepath):
    return resources.files(glyphsLib).joinpath("data").joinpath(filepath)


def copy_data_files():
    target_dir = script_dir()
    for target in ["GlyphData.xml", "GlyphData_Ideographs.xml"]:
        file = get_data_file(target)
        target = os.path.join(target_dir, target)
        with file.open("rb") as source, open(target, "wb") as dest:
            shutil.copyfileobj(source, dest)

def write_version_file():
    version = glyphsLib.__version__
    with open(os.path.join(script_dir(), 'VERSION'), 'w') as f:
        f.write(f"XML files copied from glyphsLib version {version}.\n"
                "(this file generated by update.py)\n")

def main(_):
    copy_data_files()
    write_version_file()


if __name__ == "__main__":
    main(None)
