## ###
# IP: GHIDRA
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##
import os
import inspect
from typing import Sequence


def merge(xml_base: str, xml_out: str, xml_updates: Sequence[str]) -> None:
    frame = inspect.currentframe()
    if frame is None:
        raise AssertionError("we're cooked")
    rmi = os.path.dirname(inspect.getfile(frame))

    warning = "This file was autogenerated using build_xml.  DO NOT EDIT."

    # This appears to be necessitated by path issue, i.e. merge.xsl uses "document"
    # and the Windows version of lxml doesn't do the right thing
    if os.name == 'nt':
        import subprocess

        ps_script = rmi+'/merge.ps1'
        updates = " ".join(xml_updates)
        command = [
            "powershell.exe",
            "-ExecutionPolicy", "Bypass",
            "-File", ps_script,
            "-XmlInput", xml_base,
            "-RmiDir", rmi,
            "-XmlOutput", xml_out,
            "-XmlUpdates", updates
        ]
        try:
            result = subprocess.run(command, capture_output=True, text=True)
            print(result.stdout)
        except subprocess.CalledProcessError as e:
            print(f"Error: {e.stderror}")
    else:
        from lxml import etree

        merge_doc = etree.parse(xml_base)
        warning_node = etree.Comment(warning)
        root = merge_doc.getroot()
        root.insert(0, warning_node)

        xslt_doc = etree.parse(rmi+'/xml/merge.xsl')
        transform = etree.XSLT(xslt_doc)
        for xml_update in xml_updates:
            merge_doc = transform(
                merge_doc, fileName=etree.XSLT.strparam(xml_update))
        with open(xml_out, "wb") as f:
            f.write(merge_doc)
