#!/usr/bin/python3
# encoding=utf-8
#
# Copyright © 2022 Simon McVittie
# SPDX-License-Identifier: GPL-2.0-or-later

import os
import subprocess
import sys
import tempfile


def main(source: str, layer: str, output: str) -> None:
    with tempfile.TemporaryDirectory() as temp:
        subprocess.run(
            [
                'xmlstarlet',
                'ed',
                '-d',
                ("//*[local-name() = 'g' and @inkscape:groupmode = 'layer' "
                 "and @id != '{}']".format(layer)),
            ],
            check=True,
            stdin=open(source, 'r'),
            stdout=open(os.path.join(temp, 'layer.svg'), 'w'),
        )
        subprocess.run(
            [
                'inkscape',
                '--export-area-page',
                '--export-plain-svg',
                '--export-filename=' + output,
                os.path.join(temp, 'layer.svg'),
            ],
            check=True,
            stdin=open(os.path.join(temp, 'layer.svg'), 'r'),
        )


if __name__ == '__main__':
    main(sys.argv[1], sys.argv[2], sys.argv[3])
