#!/usr/bin/python3
# Split the upstream default.xml engine list into one snippet per <engine>,
# named after the engine, so that each input-method package can ship exactly
# the snippet for the engine it provides. The shared list-engines wrapper
# concatenates whichever snippets are installed.
#
# Usage: split-engines.py <default.xml> <output-dir>

import os
import sys
import xml.dom.minidom


def main():
    src, outdir = sys.argv[1], sys.argv[2]
    dom = xml.dom.minidom.parse(src)
    os.makedirs(outdir, exist_ok=True)

    engines = dom.getElementsByTagName('engine')
    if not engines:
        sys.exit('no <engine> elements found in %s' % src)

    for engine in engines:
        name = engine.getElementsByTagName('name')[0].childNodes[0].data.strip()
        path = os.path.join(outdir, name + '.xml')
        with open(path, 'w', encoding='utf-8') as f:
            f.write(engine.toxml())
            f.write('\n')


if __name__ == '__main__':
    main()
