## ###
# 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.
##
param (
	[string]$XmlInput,
	[string]$RmiDir,
	[string]$XmlOutput,
	[string]$XmlUpdates
)

Write-Host "Compositing schema..."
$warning = $RmiDir+"warning.xml"
$xslFile = $RmiDir+"merge.xsl"
$xslt = New-Object System.Xml.Xsl.XslCompiledTransform
$settings = New-Object System.Xml.Xsl.XsltSettings($true, $false)
$resolver = New-Object System.Xml.XmlUrlResolver
$xslt.Load((Resolve-Path $xslFile), $settings, $resolver)

$workingFile = Join-Path $pwd "current.xml"
Copy-Item $XmlInput $workingFile -Force
$comment = "<!-- This file was autogenerated using build_xml.  DO NOT EDIT.-->`r`n"
$content = Get-Content $workingFile -Raw
Set-Content $workingFile -Value ($comment + $content) -NoNewLine

foreach ($fileName in ($XmlUpdates -split " ")) {
	if (Test-Path $fileName) {
		$scratch = Join-Path $pwd "temp.xml"
		
		$xsltArgs = New-Object System.Xml.Xsl.XsltArgumentList
		$xsltArgs.AddParam("fileName", "", (Resolve-Path $fileName).Path)
		
		$writer = [System.Xml.XmlWriter]::Create($scratch, $xslt.OutputSettings)
		try {
			$xslt.Transform((Resolve-Path $workingFile).Path, $xsltArgs, $writer)
			$writer.Close()
			$writer.Dispose()
	
			Move-Item $scratch $workingFile -Force
		} 
		catch {
			$writer.Close()
			Write-Error "File not found: $fileName"
		}
	}
}
Move-Item $workingFile $XmlOutput -Force
Write-Host "Transformation finished"
