source/Public/Set-RJAutomationAccount.ps1

function Set-RJAutomationAccount {
    <#
    .SYNOPSIS
    Deploys RealmJoin Automation Account infrastructure to Azure.
 
    .DESCRIPTION
    Deploys the RealmJoin Automation Account with a system-assigned managed identity and
    assigns required permissions (Microsoft Graph, Exchange, Defender, SharePoint).
 
    Uses bundled ARM templates (JSON). Device code authentication is required for proper
    consent with ARM Microsoft Graph extension operations.
 
    Prerequisites:
    - Az.Accounts and Az.Resources PowerShell modules
    - Resource group must already exist
 
    .PARAMETER ResourceGroupName
    The name of the resource group to deploy to (must exist).
 
    .PARAMETER AutomationAccountName
    Optional. The name of the Automation Account. If not provided, a unique name is auto-generated.
 
    .PARAMETER SubscriptionId
    Optional. The Azure subscription ID to deploy to. If not provided, uses the current context.
 
    .PARAMETER Token
    Optional. The RealmJoin onboarding token. When provided, registers the automation account with RealmJoin API.
 
    .PARAMETER WhatIf
    Shows what would be deployed without actually performing the deployment.
 
    .EXAMPLE
    Set-RJAutomationAccount -ResourceGroupName "rg-realmjoin"
 
    .EXAMPLE
    Set-RJAutomationAccount -ResourceGroupName "rg-realmjoin" -AutomationAccountName "my-aa"
 
    .EXAMPLE
    Set-RJAutomationAccount -ResourceGroupName "rg-realmjoin" -SubscriptionId "00000000-0000-0000-0000-000000000000"
 
    .EXAMPLE
    Set-RJAutomationAccount -ResourceGroupName "rg-realmjoin" -WhatIf
    Shows what resources would be deployed without actually deploying.
 
    .EXAMPLE
    Set-RJAutomationAccount -ResourceGroupName "rg-realmjoin" -Token "your-token"
    Deploys and registers with the RealmJoin API.
    #>


    [CmdletBinding(SupportsShouldProcess)]
    param(
        [Parameter(Mandatory)]
        [string]$ResourceGroupName,

        [string]$AutomationAccountName,

        [string]$SubscriptionId,

        [string]$Token
    )

    begin {
        Write-Verbose "Set-RJAutomationAccount: Starting"
    }

    process {
        if (-not (Test-RJModuleVersion)) {
            # Module is outdated - exit gracefully without throwing
            return
        }

        # Initialize Az modules
        Write-Information "Initializing required Azure modules..."
        if (-not (Initialize-RequiredModule)) {
            Write-Verbose "Azure module initialization failed - cannot proceed"
            return
        }

        # Connect to Azure
        $connectParams = @{}
        if ($SubscriptionId) { $connectParams.SubscriptionId = $SubscriptionId }
        $context = Connect-RJAzureContext @connectParams
        if ($null -eq $context) {
            Write-Information "Operation cancelled."
            return
        }

        # Verify resource group
        $null = Test-ResourceGroup -ResourceGroupName $ResourceGroupName

        if ($PSCmdlet.ShouldProcess("Resource Group: $ResourceGroupName", "Deploy RealmJoin Automation Account")) {
            Write-Information ""
            Write-Information "========================================"
            Write-Information "RealmJoin Automation Account Deployment"
            Write-Information "========================================"
            Write-Information ""

            # Deploy
            $deployParams = @{
                ResourceGroupName = $ResourceGroupName
            }
            if ($AutomationAccountName) {
                $deployParams.AutomationAccountName = $AutomationAccountName
            }

            $result = Set-RJAutomationAccountResource @deployParams

            if (-not $result.Success) {
                throw "Automation Account deployment failed"
            }

            # Optional API registration
            if ($Token) {
                Write-Information ""
                Write-Information "--- RealmJoin API Registration ---"
                $additionalData = @{
                    tenantId              = $context.TenantId
                    subscriptionId        = $context.SubscriptionId
                    resourceGroupName     = $ResourceGroupName
                    automationAccountName = $result.Outputs.AutomationAccountName
                }
                Invoke-RJOnboarding -Token $Token -ApiUrl (Get-RealmJoinTenantAzureResourcesOnboardingApiUrl) -AdditionalData $additionalData
            }

            # Summary
            Write-Information ""
            Write-Information "========================================"
            Write-Information "Deployment Complete!"
            Write-Information "========================================"
            Write-Information "Automation Account: $($result.Outputs.AutomationAccountName)"
            Write-Information "Resource ID: $($result.Outputs.AutomationAccountId)"
            Write-Information "Managed Identity: $($result.Outputs.AutomationAccountPrincipalId)"
            Write-Information "Permissions: Graph=$($result.Outputs.GraphPermissionsCount), Exchange=$($result.Outputs.ExchangePermissionsCount), Defender=$($result.Outputs.DefenderPermissionsCount), SharePoint=$($result.Outputs.SharePointPermissionsCount)"
            Write-Information ""
        }
        else {
            # WhatIf: show analysis
            $analysis = Get-RJAzureResourceAnalysis -ResourceGroupName $ResourceGroupName `
                -DeployAutomationAccount $true `
                -DeployLogAnalytics $false `
                -AutomationAccountName $AutomationAccountName
            Show-RJAzureResourceAnalysis -Analysis $analysis
        }
    }

    end {
        Write-Verbose "Set-RJAutomationAccount: Completed"
    }
}