<commit_before><#
# script to update azure arm template resource settings
download:
(new-object net.webclient).DownloadFile("https://raw.githubusercontent.com/jagilber/powershellScripts/master/azure-az-patch-resource.ps1","$pwd\azure-az-patch-resource.ps1")
.\azure-az-patch-resource.ps1 -resourceGroupName {{ resource group name }} -resourceName {{ resource name }} [-patch]

.EXAMPLE
#>
param (
    [string]$resourceGroupName = '',
    [string[]]$resourceNames = '',
    [string]$templateJsonFile = '.\template.json', 
    [string]$apiVersion = '' ,
    [string]$schema = 'http://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json',
    [int]$sleepSeconds = 1, 
    [switch]$patch
)

$ErrorActionPreference = 'continue'
$VerbosePreference = 'continue'
$global:resourceTemplateObj = @{}

function main () {
    $global:startTime = get-date

    if (!$resourceGroupName -or !$templateJsonFile) {
        write-error 'pas arguments'
        return
    }

    if (!$resourceNames) {
        $resourceNames = @((get-azresource -resourceGroupName $resourceGroupName).Name)
    }

    if (!(Get-AzContext)) {
        Connect-AzAccount
    }

    $error.Clear()
    display-settings

    if ($error) {
        Write-Warning "error enumerating resource"
        return
    }

    $deploymentName = "$resourceGroupName-$((get-date).ToString("yyyyMMdd-HHmms"))"

    if ($patch) {
        remove-jobs
        if (!(deploy-template -resourceNames $resourceNames)) { return }
        wait-jobs
    }
    else {
        export-template -resourceNames $resourceNames
    }

    Write-Progress -Completed -Activity "complete"
    display-settings
    write-host 'finished. template stored in $global:resourceTemplateObj' -ForegroundColor Cyan
}

function deploy-template($resourceNames) {
    $json = get-content -raw $templateJsonFile | convertfrom-json
    if ($error -or !$json -or !$json.resources) {
        write-error "invalid template file $templateJsonFile"
        return
    }

    $templateJsonFile = Resolve-Path $templateJsonFile
    $tempJsonFile = "$([io.path]::GetDirectoryName($templateJsonFile))\$([io.path]::GetFileNameWithoutExtension($templateJsonFile)).temp.json"
    $resources = @($json.resources | ? Name -imatch ($resourceNames -join '|'))

    create-jsonTemplate -resources $resources -jsonFile $tempJsonFile | Out-Null
    $error.Clear()
    $result = Test-AzResourceGroupDeployment -ResourceGroupName $resourceGroupName -TemplateFile $tempJsonFile -Verbose

    if (!$error -and !$result) {
        write-host "patching resource with $tempJsonFile" -ForegroundColor Yellow
        start-job -ScriptBlock {
            param ($resourceGroupName, $tempJsonFile, $deploymentName)
            $VerbosePreference = 'continue'
            write-host "using file: $tempJsonFile"
            New-AzResourceGroupDeployment -Name $deploymentName `
                -ResourceGroupName $resourceGroupName `
                -DeploymentDebugLogLevel All `
                -TemplateFile $tempJsonFile `
                -Verbose
            } -ArgumentList $resourceGroupName, $tempJsonFile, $deploymentName
    }
    else {
        write-error "template validation failed`r`n$($error | out-string)`r`n$result"
        return $false
    }

    if ($error) {
        return $false
    }
    else {
        #Remove-Item $tempJsonFile -Force
        return $true
    }
}

function export-template($resourceNames) {
    write-host "exporting template to $templateJsonFile" -ForegroundColor Yellow
    $resources = [collections.arraylist]@()
    $azResourceGroupLocation = @(get-azresource -ResourceGroupName $resourceGroupName)[0].Location
    $resourceProviders = Get-AzResourceProvider -Location $azResourceGroupLocation
    
    foreach ($name in $resourceNames) {
        # convert az resource to arm template
        $azResource = get-azresource -Name $name -ResourceGroupName $resourceGroupName -ExpandProperties
        $resourceProvider = $resourceProviders | where-object ProviderNamespace -ieq $azResource.ResourceType.split('/')[0]
        $rpType = $resourceProvider.ResourceTypes | Where-Object ResourceTypeName -ieq $azResource.ResourceType.split('/')[1]
        $resourceApiVersion = $apiVersion

        if (!$apiVersion) {
            $resourceApiVersion = $rpType.ApiVersions[0]
        }

        [void]$resources.Add(@{
                apiVersion = $resourceApiVersion
                #dependsOn  = @()
                type       = $azResource.ResourceType
                location   = $azResource.Location
                id         = $azResource.ResourceId
                name       = $azResource.Name
                tags       = $azResource.Tags
                properties = $azResource.properties
            })
    }

    if (!(create-jsonTemplate -resources $resources -jsonFile $templateJsonFile)) { return }
    return
}

function create-jsonTemplate([collections.arraylist]$resources, [string]$jsonFile) {
    try {
        $resourceTemplate = @{ 
            '$schema'      = $schema
            contentVersion = "1.0.0.0"
            resources      = $resources
        } | convertto-json -depth 99

        $resourceTemplate | out-file $jsonFile

        write-host $resourceTemplate -ForegroundColor Cyan
        write-host "template exported to $templateJsonFile" -ForegroundColor Yellow
        write-host "to update arm resource, modify $templateJsonFile.  when finished, execute script with -patch to update resource" -ForegroundColor Yellow
        . $templateJsonFile

        $global:resourceTemplateObj = $resourceTemplate | convertfrom-json
        return $true
    }
    catch { 
        write-error "$($_)`r`n$($error | out-string)"
        return $false
    }
}
function display-settings() {
    foreach ($name in $resourceNames) {
        $settings += Get-AzResource -ResourceGroupName $resourceGroupName `<commit_msg>testing sort change<commit_after><#
# script to update azure arm template resource settings
download:
(new-object net.webclient).DownloadFile("https://raw.githubusercontent.com/jagilber/powershellScripts/master/azure-az-patch-resource.ps1","$pwd\azure-az-patch-resource.ps1")
.\azure-az-patch-resource.ps1 -resourceGroupName {{ resource group name }} -resourceName {{ resource name }} [-patch]

.EXAMPLE
#>
param (
    [string]$resourceGroupName = '',
    [string[]]$resourceNames = '',
    [string]$templateJsonFile = '.\template.json', 
    [string]$apiVersion = '' ,
    [string]$schema = 'http://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json',
    [int]$sleepSeconds = 1, 
    [switch]$patch
)

$ErrorActionPreference = 'continue'
$VerbosePreference = 'continue'
$global:resourceTemplateObj = @{}

function main () {
    $global:startTime = get-date

    if (!$resourceGroupName -or !$templateJsonFile) {
        write-error 'pas arguments'
        return
    }

    if (!$resourceNames) {
        $resourceNames = @((get-azresource -resourceGroupName $resourceGroupName).Name)
    }

    if (!(Get-AzContext)) {
        Connect-AzAccount
    }

    $error.Clear()
    display-settings

    if ($error) {
        Write-Warning "error enumerating resource"
        return
    }

    $deploymentName = "$resourceGroupName-$((get-date).ToString("yyyyMMdd-HHmms"))"

    if ($patch) {
        remove-jobs
        if (!(deploy-template -resourceNames $resourceNames)) { return }
        wait-jobs
    }
    else {
        export-template -resourceNames $resourceNames
    }

    Write-Progress -Completed -Activity "complete"
    display-settings
    write-host 'finished. template stored in $global:resourceTemplateObj' -ForegroundColor Cyan
}

function deploy-template($resourceNames) {
    $json = get-content -raw $templateJsonFile | convertfrom-json
    if ($error -or !$json -or !$json.resources) {
        write-error "invalid template file $templateJsonFile"
        return
    }

    $templateJsonFile = Resolve-Path $templateJsonFile
    $tempJsonFile = "$([io.path]::GetDirectoryName($templateJsonFile))\$([io.path]::GetFileNameWithoutExtension($templateJsonFile)).temp.json"
    $resources = @($json.resources | ? Name -imatch ($resourceNames -join '|'))

    create-jsonTemplate -resources $resources -jsonFile $tempJsonFile | Out-Null
    $error.Clear()
    $result = Test-AzResourceGroupDeployment -ResourceGroupName $resourceGroupName -TemplateFile $tempJsonFile -Verbose

    if (!$error -and !$result) {
        write-host "patching resource with $tempJsonFile" -ForegroundColor Yellow
        start-job -ScriptBlock {
            param ($resourceGroupName, $tempJsonFile, $deploymentName)
            $VerbosePreference = 'continue'
            write-host "using file: $tempJsonFile"
            New-AzResourceGroupDeployment -Name $deploymentName `
                -ResourceGroupName $resourceGroupName `
                -DeploymentDebugLogLevel All `
                -TemplateFile $tempJsonFile `
                -Verbose
            } -ArgumentList $resourceGroupName, $tempJsonFile, $deploymentName
    }
    else {
        write-error "template validation failed`r`n$($error | out-string)`r`n$result"
        return $false
    }

    if ($error) {
        return $false
    }
    else {
        #Remove-Item $tempJsonFile -Force
        return $true
    }
}

function export-template($resourceNames) {
    write-host "exporting template to $templateJsonFile" -ForegroundColor Yellow
    $resources = [collections.arraylist]@()
    $azResourceGroupLocation = @(get-azresource -ResourceGroupName $resourceGroupName)[0].Location
    $resourceProviders = Get-AzResourceProvider -Location $azResourceGroupLocation
    
    foreach ($name in $resourceNames) {
        # convert az resource to arm template
        $azResource = get-azresource -Name $name -ResourceGroupName $resourceGroupName -ExpandProperties
        $resourceProvider = $resourceProviders | where-object ProviderNamespace -ieq $azResource.ResourceType.split('/')[0]
        $rpType = $resourceProvider.ResourceTypes | Where-Object ResourceTypeName -ieq $azResource.ResourceType.split('/')[1]
        $resourceApiVersion = $apiVersion

        if (!$apiVersion) {
            $resourceApiVersion = $rpType.ApiVersions[0]
        }

        [void]$resources.Add(@{
                apiVersion = $resourceApiVersion
                #dependsOn  = @()
                type       = $azResource.ResourceType
                location   = $azResource.Location
                id         = $azResource.ResourceId
                name       = $azResource.Name
                tags       = $azResource.Tags
                properties = $azResource.properties
            })
    }

    if (!(create-jsonTemplate -resources $resources -jsonFile $templateJsonFile)) { return }
    return
}

function create-jsonTemplate([collections.arraylist]$resources, [string]$jsonFile) {
    try {
        $resourceTemplate = @{ 
            resources      = $resources
            '$schema'      = $schema
            contentVersion = "1.0.0.0"
        } | convertto-json -depth 99

        $resourceTemplate | out-file $jsonFile

        write-host $resourceTemplate -ForegroundColor Cyan
        write-host "template exported to $templateJsonFile" -ForegroundColor Yellow
        write-host "to update arm resource, modify $templateJsonFile.  when finished, execute script with -patch to update resource" -ForegroundColor Yellow
        . $templateJsonFile

        $global:resourceTemplateObj = $resourceTemplate | convertfrom-json
        return $true
    }
    catch { 
        write-error "$($_)`r`n$($error | out-string)"
        return $false
    }
}
function display-settings() {
    foreach ($name in $resourceNames) {
        $settings += Get-AzResource -ResourceGroupName $resourceGroupName `
{'fraction_non_alphanumeric': 0.11435853865760408, 'fraction_numerical': 0.003738317757009346, 'mean_word_length': 2.776387552133462, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1433124', 'n_tokens_mistral': 3255, 'n_tokens_neox': 3156, 'n_words': 684}