# <copyright file="_executeTemplate.ps1" company="Endjin Limited">
# Copyright (c) Endjin Limited. All rights reserved.
# </copyright>

function _executeTemplate
    param (
        [string] $TemplatePath,

        [string] $OutputPath,

        [switch] $Force,

        [array] $TemplateParameters

    # Convert the format of the 'ValueFromRemainingArguments' parameters into a hashtable
    # format required by EPS' -Binding parameter
    $bindings = @{}
    for ($i=0; $i -lt $TemplateParameters.Count; $i+=2) {
        $bindings.Add($TemplateParameters[$i].TrimStart("-").TrimEnd(":"), $TemplateParameters[$i+1])

    # Add a binding for the globally-used InvokeBuild module version
    $bindings.Add("InvokeBuildModuleVersion", $InvokeBuildModuleVersion)

    # Resolve the provided path so we have absolute path before doing further path manipulation
    $OutputPath = [IO.Path]::GetFullPath($OutputPath, $PWD)

    if ( !(Test-Path $OutputPath) -or $Force ) {
        $outputDir = Split-Path -Parent $OutputPath
        # Ensure the containing folders for the output exist
        if (!(Test-Path $outputDir)) {
            New-Item -ItemType Directory -Path $outputDir

        $newFileContent = Invoke-EpsTemplate -Path $TemplatePath -Binding $bindings
        Set-Content -Value $newFileContent -Path $OutputPath -Force:$Force
    else {
        Write-Verbose "The output file '$OutputPath' already exists - specify '-Force' to overwrite"