lib/Recipes.ps1



# Recipes
Function Get-TMRecipe {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $false)]
        [String]$TMSession = 'Default',
        
        [Parameter(Mandatory = $false)]
        [String]$Name,
        
        [Parameter(Mandatory = $false)]
        [String]$Server = $global:TMSessions[$TMSession].TMServer,
        
        [Parameter(Mandatory = $false)]
        [Bool]$AllowInsecureSSL = $global:TMSessions[$TMSession].AllowInsecureSSL,
        
        [Parameter(Mandatory = $false)]
        [Switch]$ResetIDs,
        
        [Parameter(Mandatory = $false)]
        [String]$SaveCodePath,

        [Parameter(Mandatory = $false)]
        [Switch]$Passthru

    )

    ## Get Session Configuration
    $TMSessionConfig = $global:TMSessions[$TMSession]
    if (-not $TMSessionConfig) {
        Write-Host 'TMSession: [' -NoNewline
        Write-Host $TMSession -ForegroundColor Cyan
        Write-Host '] was not Found. Please use the New-TMSession command.'
        Throw 'TM Session Not Found. Use New-TMSession command before using features.'
    }

    #Honor SSL Settings
    $TMCertSettings = $TMSessionConfig.AllowInsecureSSL ? @{SkipCertificateCheck = $true } : @{SkipCertificateCheck = $false }

    # Format the uri
    $instance = $Server.Replace('/tdstm', '').Replace('https://', '').Replace('http://', '')
    $uri = "https://$instance/tdstm/ws/cookbook/recipe/list?archived=n&context=All"

    try {
        $response = Invoke-WebRequest -Method Get -Uri $uri -WebSession $TMSessionConfig.TMWebSession @TMCertSettings
    }
    catch {
        return $_
    }

    if ($response.StatusCode -in @(200, 204)) {
        $Result = ($response.Content | ConvertFrom-Json).data.list
    }
    else {
        return 'Unable to collect Recipes.'
    }
    
    ## Get each recipe's Source Code in the list
    for ($i = 0; $i -lt $Result.Count; $i++) {
        
        $uri = "https://$instance/tdstm/ws/cookbook/recipe/$($Result[$i].recipeId)"

        try {
            $response = Invoke-WebRequest -Method Get -Uri $uri -WebSession $TMSessionConfig.TMWebSession @TMCertSettings
        }
        catch {
            return $_
        }

        if ($response.StatusCode -in @(200, 204)) {
            $Result[$i] = ($response.Content | ConvertFrom-Json).data
        }
        else {
            return 'Unable to collect Recipe.'
        }
    }

    if ($ResetIDs) {
        for ($i = 0; $i -lt $Result.Count; $i++) {
            
            ## Null the Recipe ID and Event
            $Result[$i].recipeId = $null
            if ($Result[$i].context.eventId) { $Result[$i].context.eventId = $null }

            ## Replace customNN values with a token with the field spec name
            

        }
    }

    ## Return the details
    if ($Name) {
        $Result = $Result | Where-Object { $_.name -eq $Name }
    } 
    else {
        $Result = $Result
    }
    
    ## Save the Code Files to a folder
    if ($SaveCodePath) {

        ## Save Each of the Script Source Data
        foreach ($Item in $Result) {

            ## Get a FileName safe version of the Provider Name
            $SafeScriptName = Get-FilenameSafeString $Item.name

            ## Create the Provider Action Folder path
            Test-FolderPath -FolderPath $SaveCodePath

            ## Create a File ame for the Action
            $ScriptPath = Join-Path $SaveCodePath ($SafeScriptName + '.TMRecipe.groovy')

            ## Build a config of the important References
            $TMConfig = [PSCustomObject]@{
                RecipeName    = $Item.name
                Description   = $Item.description
                VersionNumber = $Item.versionNumber
                HasWip        = $Item.hasWip
            } | ConvertTo-Json | Out-String

            ## Create a Script String output
            $ScriptOutput = [System.Text.StringBuilder]::new()
            [void]$ScriptOutput.AppendLine('/*********TransitionManager-Recipe-Script*********')
            [void]$ScriptOutput.AppendLine()
        
            [void]$ScriptOutput.AppendLine($TMConfig)
            [void]$ScriptOutput.AppendLine()
        
            [void]$ScriptOutput.AppendLine('*********TransitionManager-Recipe-Script*********/')
    
            [void]$ScriptOutput.AppendLine()
            [void]$ScriptOutput.AppendLine()
    
            ## Write the Script to the Configuration
            [void]$ScriptOutput.AppendLine($Item.sourceCode)
            [void]$ScriptOutput.AppendLine()

            ## Start Writing the Content of the Script (Force to overwrite any existing files)
            Set-Content -Path $ScriptPath -Force -Value $ScriptOutput.toString()
        }
    } 

    if ($Passthru -or !$SaveCodePath) {
        return $Result
    }
}


Function New-TMRecipe {
    param(
        [Parameter(Mandatory = $false)][String]$TMSession = 'Default',
        [Parameter(Mandatory = $true)][PSObject]$Recipe,
        [Parameter(Mandatory = $false)][String]$Server = $global:TMSessions[$TMSession].TMServer,
        [Parameter(Mandatory = $false)]$AllowInsecureSSL = $global:TMSessions[$TMSession].AllowInsecureSSL,
        [Parameter(Mandatory = $false)][Switch]$Update, 
        [Parameter(Mandatory = $false)][Switch]$PassThru
    )
    if ($global:TMSessions[$TMSession].TMVersion -like '4.6*') {
        New-TMRecipe46 @PSBoundParameters
    }
    else {
        New-TMRecipe47 @PSBoundParameters
    }
}

Function New-TMRecipe46 {
    param(
        [Parameter(Mandatory = $false)][String]$TMSession = 'Default',
        [Parameter(Mandatory = $true)][PSObject]$Recipe,
        [Parameter(Mandatory = $false)][String]$Server = $global:TMSessions[$TMSession].TMServer,
        [Parameter(Mandatory = $false)]$AllowInsecureSSL = $global:TMSessions[$TMSession].AllowInsecureSSL,
        [Parameter(Mandatory = $false)][Switch]$PassThru

    )
    ## Get Session Configuration
    $TMSessionConfig = $global:TMSessions[$TMSession]
    if (-not $TMSessionConfig) {
        Write-Host 'TMSession: [' -NoNewline
        Write-Host $TMSession -ForegroundColor Cyan
        Write-Host '] was not Found. Please use the New-TMSession command.'
        Throw 'TM Session Not Found. Use New-TMSession command before using features.'
    }

    #Honor SSL Settings
    if ($TMSessionConfig.AllowInsecureSSL) {
        $TMCertSettings = @{SkipCertificateCheck = $true }
    }
    else { 
        $TMCertSettings = @{SkipCertificateCheck = $false }
    }

    # Write-Host "Creating Recipe: "$Recipe.Name

    ## Check for existing credential
    $RecipeCheck = Get-TMRecipe -Name $Recipe.Name -TMSession $TMSession
    if ($RecipeCheck) {
        return $RecipeCheck
    }
    else {
        ## No Recipe exists. Create it
        $instance = $Server.Replace('/tdstm', '')
        $instance = $instance.Replace('https://', '')
        $instance = $instance.Replace('http://', '')
    
        $uri = 'https://'
        $uri += $instance
        $uri += '/tdstm/ws/cookbook/recipe'

        ## Add Recipe Shell on server
        $PostBody = @{
            name        = $Recipe.Name
            description = $Recipe.description
        }
        
        Set-TMHeaderContentType -ContentType 'Form' -TMSession $TMSession
        
        $response = Invoke-WebRequest -Method Post -Uri $uri -WebSession $TMSessionConfig.TMWebSession -Body $PostBody @TMCertSettings
        if ($response.StatusCode -eq 200) {
            $responseContent = $response.Content | ConvertFrom-Json
            if ($responseContent.status -eq 'success') {
                
                ## Created a new recipe ID, update the Recipe Object and save it.
                $NewRecipeID = $responseContent.data.recipeId

                $UpdatedRecipe = @{
                    recipeId              = $NewRecipeID
                    name                  = $Recipe.name
                    description           = $Recipe.description
                    createdBy             = $Recipe.createdBy
                    versionNumber         = $Recipe.versionNumber
                    releasedVersionNumber = $Recipe.releasedVersionNumber
                    recipeVersionId       = $Recipe.releasedVersionId
                    hasWIP                = $Recipe.hasWIP
                    sourceCode            = $Recipe.sourceCode
                    changelog             = $Recipe.changelog
                    clonedFrom            = $Recipe.clonedFrom
                }

                # Update the newly created recipe with the data
                $uri = 'https://'
                $uri += $instance
                $uri += '/tdstm/ws/cookbook/recipe/' + $NewRecipeID
                $response = Invoke-WebRequest -Method Post -Uri $uri -WebSession $TMSessionConfig.TMWebSession -Body $UpdatedRecipe @TMCertSettings
                if ($response.StatusCode -eq 200) {
                    $responseContent = $response.Content | ConvertFrom-Json
                    if ($responseContent.status -eq 'success') {
                        if ($PassThru) { return $UpdatedRecipe }
                    }
                    else {
                        throw 'Unable to add Recipe.'
                    }
                }
                else {
                    throw 'Unable to add Recipe.'
                }

                ## Publish the Recipe if there is no WIP
                if ($Recipe.hasWip -eq 'no') {

                    ## Set the Request to a Form post
                    Set-TMHeaderContentType -ContentType 'FORM'
                    $FormPostData = @{
                        recipeId              = $Recipe.id
                        name                  = $Recipe.name
                        description           = $Recipe.description
                        createdBy             = $Recipe.createdBy
                        lastUpdated           = $Recipe.lastUpdated
                        versionNumber         = $Recipe.versionNumber
                        releasedVersionNumber = $Recipe.releasedVersionNumber
                        hasWip                = $true
                        sourceCode            = $Recipe.sourceCode
                        changelog             = ''
                        clonedFrom            = ''
                    }
                    
                    ## Create the URL and Post the data
                    $PublishURI = "https://$Instance/tdstm/ws/cookbook/recipe/release/$($Recipe.id)"

                    ## Try the Request
                    $response = Invoke-WebRequest -Method 'Post' -Uri $PublishURI -WebSession $TMSessionConfig.TMWebSession -Body $FormPostData @TMCertSettings
                    if ($response.StatusCode -eq 200) {
                        $responseContent = $response.Content | ConvertFrom-Json
                        if ($responseContent.status -eq 'success') {
                            if ($PassThru) { return }
                        }
                        else {
                            throw 'Unable to Publish Recipe.'
                        }
                    }
                    else {
                        throw 'Unable to Publish Recipe.'
                    }
                }
            }
            else {
                throw 'Unable to add Recipe.'
            }
        }
        else {
            throw 'Unable to add Recipe.'
        }
    }    
}
Function New-TMRecipe47 {
    param(
        [Parameter(Mandatory = $false)][String]$TMSession = 'Default',
        [Parameter(Mandatory = $true)][PSObject]$Recipe,
        [Parameter(Mandatory = $false)][String]$Server = $global:TMSessions[$TMSession].TMServer,
        [Parameter(Mandatory = $false)]$AllowInsecureSSL = $global:TMSessions[$TMSession].AllowInsecureSSL,
        [Parameter(Mandatory = $false)][Switch]$Update,
        [Parameter(Mandatory = $false)][Switch]$PassThru
    )

    ## Get Session Configuration
    $TMSessionConfig = $global:TMSessions[$TMSession]
    if (-not $TMSessionConfig) {
        Write-Host 'TMSession: [' -NoNewline
        Write-Host $TMSession -ForegroundColor Cyan
        Write-Host '] was not Found. Please use the New-TMSession command.'
        Throw 'TM Session Not Found. Use New-TMSession command before using features.'
    }

    ## Strip Instance Name out
    $instance = $Server.Replace('/tdstm', '')
    $instance = $instance.Replace('https://', '')
    $instance = $instance.Replace('http://', '')

    #Honor SSL Settings
    if ($TMSessionConfig.AllowInsecureSSL) {
        $TMCertSettings = @{SkipCertificateCheck = $true }
    }
    else { 
        $TMCertSettings = @{SkipCertificateCheck = $false }
    }

    ## Check for existing credential, or Create a shell
    $RecipeCheck = Get-TMRecipe -Name $Recipe.Name -TMSession $TMSession
    if ($RecipeCheck) {
        
        ## If Update is enabled, set the RecipeID for the update
        if ($Update) {
            $NewRecipeID = $RecipeCheck.recipeId
        }
        else {

            ## If Passthru is enabled, return the object
            if ($PassThru) {
                return $RecipeCheck
            }
            else {
                return
            }
        }
    }
    else {

        ## The Recipe needs to be created. Start by posting the name to get an ID
        $uri = 'https://'
        $uri += $instance
        $uri += '/tdstm/ws/cookbook/recipe'
    
        ## Create a new Recipe
        $CreateNewRecipe = @{
            name        = $Recipe.name
            description = $Recipe.description
        } #| ConvertTo-Json
        
        ## Send the New recipe to the server
        Set-TMHeaderContentType -ContentType 'Form' -TMSession $TMSession
        $response = Invoke-WebRequest -Method Post -Uri $uri -WebSession $TMSessionConfig.TMWebSession -Body $CreateNewRecipe @TMCertSettings
        if ($response.StatusCode -eq 200) {
        
            ## Convert the response content
            $responseContent = $response.Content | ConvertFrom-Json

            ## If Successful
            if ($responseContent.status -eq 'success') {
                
                ## Created a new recipe ID, update the Recipe Object and save it.
                $NewRecipeID = $responseContent.data.recipeId
            
            }
            else {
                throw "Unable to add Recipe. $($ResponseContent.errors))"
            }
        }
        else {
            throw 'Unable to add Recipe.'
        }
    }
    
    ##
    ## Update or Create the Recipe
    ##

    $RecipeSourceCode = $Recipe.sourceCode

    $NewRecipe = Get-TMRecipe -Name $Recipe.name
    if ($NewRecipe) {
        $Recipe = $NewRecipe
    }

    ## With the Existing or New RecipeID Update the Recipe Data
    $UpdatedRecipe = @{
        recipeId              = $NewRecipeID
        name                  = $Recipe.name
        description           = $Recipe.description
        createdBy             = $Recipe.createdBy
        lastUpdated           = $Recipe.lastUpdated
        versionNumber         = $Recipe.versionNumber
        releasedVersionNumber = $Recipe.releasedVersionNumber
        recipeVersionId       = $NewRecipe.recipeVersionId
        hasWIP                = $Recipe.hasWIP
        sourceCode            = $RecipeSourceCode
        changelog             = $Recipe.changelog
        clonedFrom            = $Recipe.clonedFrom
    }
        
    # Update the newly created recipe with the data
    $uri = 'https://'
    $uri += $instance
    $uri += '/tdstm/ws/cookbook/recipe/' + $NewRecipeID 
    
    ## Send the Recipe (New or Update)
    Set-TMHeaderContentType -ContentType 'Form' -TMSession $TMSession
    $response = Invoke-WebRequest -Method Post -Uri $uri -WebSession $TMSessionConfig.TMWebSession -Body $UpdatedRecipe @TMCertSettings
    if ($response.StatusCode -eq 200) {
        
        ## Convert the response content
        $responseContent = $response.Content | ConvertFrom-Json

        ## If Successful
        if ($responseContent.status -ne 'success') {
            throw "Unable to add Recipe: $($responseContent.errors)"
        }
    }

    ## If Passthru is enabled, return the Updated Recipe
    if ($PassThru) { 
        return (Get-TMRecipe -Name $Recipe.name) 
    }
}


Function Read-TMRecipeScriptFile {
    param(
        [Parameter(Mandatory = $true)]$Path
    )

    ## Name the Input File
    $Content = Get-Content -Path $Path -Raw
    $ContentLines = Get-Content -Path $Path

    ## Create Automation Token Variables Parse the Script File
    New-Variable astTokens -Force
    New-Variable astErr -Force
    $ast = [System.Management.Automation.Language.Parser]::ParseInput($Content, [ref]$astTokens, [ref]$astErr)

    ##
    ## Assess the Script Parts to get delineating line numbers
    ##
    
    ## Locate the Delimiting line
    $ConfigBlockStartLine = $astTokens | `
        Where-Object { $_.Text -like '/*********TransitionManager-Recipe-Script*********' } |`
        Select-Object -First 1 | `
        Select-Object -ExpandProperty Extent | `
        Select-Object -ExpandProperty StartLineNumber
    

    ## If the Output contains the appropriate TMD Recipe Script header
    if (-Not $ConfigBlockStartLine) {

        ## The File is not a formated export with metadata, read it as is and produce a best-effort RecipeConfig
        $RecipeConfig = @{
            recipeId      = $null
            RecipeName    = (Get-Item -Path $Path).BaseName -replace '.TMRecipe', ''
            description   = ''
            versionnumber = 1
            hasWip        = $False
        }

        $ConfigBlockEndLine = -1
    } 
    else {
        ## Find the Config Block End Header
        $ConfigBlockEndLine = $astTokens | `
            Where-Object { $_.Text -like '*********TransitionManager-Recipe-Script*********/' } |`
            Select-Object -First 1 | `
            Select-Object -ExpandProperty Extent | `
            Select-Object -ExpandProperty StartLineNumber
    
        ## Adjust the Line Numbers to capture just the JSON
        $JsonConfigBlockStartLine = $ConfigBlockStartLine + 1
        $JsonConfigBlockEndLine = $ConfigBlockEndLine - 1
    
        ##
        ## Read the Script Header to gather the configurations
        ##

        ## Get all of the lines in the header comment
        $RecipeConfigJson = $JsonConfigBlockStartLine..$JSONConfigBlockEndLine | ForEach-Object {
        
            ## Return the line for collection
            $ContentLines[$_ - 1]

        } | Out-String
    
        ## Convert the JSON string to an Object
        $RecipeConfig = $RecipeConfigJson | ConvertFrom-Json -ErrorAction 'SilentlyContinue'
    
    }

    ##
    ## Read the Script Block
    ##
    
    ## Note where the Configuration Code is located
    $StartCodeBlockLine = $ConfigBlockEndLine + 1
    $EndCodeBlockLine = $ast[-1].Extent.EndLineNumber
    
    ## Create a Text StrinBuilder to collect the Script into
    $RecipeStringBuilder = New-Object System.Text.StringBuilder

    ## For each line in the Code Block, add it to the Etl Script Code StringBuilder
    $StartCodeBlockLine..$EndCodeBlockLine | ForEach-Object {
        $RecipeStringBuilder.AppendLine($ContentLines[$_]) | Out-Null
    }

    $RecipeScriptCode = $RecipeStringBuilder.ToString()

    ## Convert the StringBuilder to a Multi-Line String
    $RecipeConfig | Add-Member -NotePropertyName 'sourceCode' -NotePropertyValue $RecipeStringBuilder.ToString() -Force

    ## Create Version Numbers
    $VersionNumber = $Recipe.VersionNumber ?? 1
    $ReleasedVersionNumber = $Recipe.ReleasedVersionNumber ?? ($Recipe.hasWIP ? $VersionNumber : -1)

    ##
    ## Assemble the Action Object
    $TMRecipe = [pscustomobject]@{
        
        ## Primary Information
        recipeId              = $RecipeConfig.recipeId ?? $null
        name                  = $RecipeConfig.RecipeName
        description           = $RecipeConfig.Description ?? ''
        versionNumber         = $VersionNumber
        
        ## Source Code
        sourceCode            = $RecipeScriptCode
        
        ## Other details for the Recipe
        dateCreated           = ($RecipeConfig.dateCreated ?? (Get-Date))
        lastUpdated           = ($RecipeConfig.lastUpdated ?? (Get-Date))
        releasedVersionNumber = $ReleasedVersionNumber
        hasWIP                = ($RecipeConfig.HasWIP ?? 'yes')
        changeLog             = ''
        clonedFrom            = ''
    }
    
    ## Return the Recipe Object
    return $TMRecipe

}
# Function Publish-TMRecipe {
# [CmdletBinding()]
# param(
# [Parameter(Mandatory = $false)]
# [String]$TMSession = 'Default',
        
# [Parameter(Mandatory = $false)]
# [String]$Name,
        
# [Parameter(Mandatory = $false)]
# [String]$Server = $global:TMSessions[$TMSession].TMServer,
        
# [Parameter(Mandatory = $false)]
# [Bool]$AllowInsecureSSL = $global:TMSessions[$TMSession].AllowInsecureSSL
# )

# ## Get Session Configuration
# $TMSessionConfig = $global:TMSessions[$TMSession]
# if (-not $TMSessionConfig) {
# Write-Host 'TMSession: [' -NoNewline
# Write-Host $TMSession -ForegroundColor Cyan
# Write-Host '] was not Found. Please use the New-TMSession command.'
# Throw 'TM Session Not Found. Use New-TMSession command before using features.'
# }

# #Honor SSL Settings
# $TMCertSettings = $TMSessionConfig.AllowInsecureSSL ? @{SkipCertificateCheck = $true } : @{SkipCertificateCheck = $false }

# ## Get the Existing Recipe to publish
# $ServerRecipe = Get-TMRecipe -Name $Name -TMSession $TMSession
# if (-Not $ServerRecipe) {
# throw 'Recipe not found'
# }

# if ($ServerRecipe.hasWIP -eq $False) {
# Write-Host 'This recipe does not have a Work In Progress, and is already released.'
# return
# }

# # Format the uri
# $instance = $Server.Replace('/tdstm', '').Replace('https://', '').Replace('http://', '')
# $Uri = "https://$Instance/tdstm/ws/cookbook/recipe/release/" + $ServerRecipe.recipeId
    
# ## Set the Request to a Form post
# Set-TMHeaderContentType -ContentType 'FORM'
# $FormPostData = @{
# recipeId = $ServerRecipe.recipeId
# name = $ServerRecipe.name
# description = $ServerRecipe.description
# createdBy = $ServerRecipe.createdBy
# lastUpdated = $ServerRecipe.lastUpdated
# versionNumber = $ServerRecipe.versionNumber
# releasedVersionNumber = $ServerRecipe.releasedVersionNumber
# recipeVersionId = $ServerRecipe.recipeVersionId
# hasWip = $ServerRecipe.hasWip
# sourceCode = $ServerRecipe.sourceCode
# changelog = $ServerRecipe.changelog
# clonedFrom = $ServerRecipe.clonedFrom
# }
                    
# ## Try the Request
# $response = Invoke-WebRequest -Method 'Post' -Uri $Uri -WebSession $TMSessionConfig.TMWebSession -Body $FormPostData @TMCertSettings
# if ($response.StatusCode -eq 200) {
# $responseContent = $response.Content | ConvertFrom-Json
# if ($responseContent.status -ne 'success') {
# Write-Error ('Unable to Publish Recipe:' + $responseContent.errors)
# }
# }
# }

function Invoke-TMRecipe {
    <#
    .SYNOPSIS
    Invokes a TransitionManager Recipe and produces a runbook.
     
    .DESCRIPTION
    This function allows a user to invoke a TransitionManager Recipe,
    choosing the Recipe, Bundles and Events related.
     
    .PARAMETER Name
    The name of the Recipe to use to Generate Tasks from
     
    .PARAMETER EventName
    The name of the Event to create tasks in
 
    .PARAMETER UseWip
    Determines if the Work In Progress recipe is used to generate tasks
     
    .PARAMETER PublishTasks
    Determines if the resulting tasks are published in the runbook or not.
     
    .PARAMETER ActivityId
    When Provided, This function will include Write-Progress Activities, using this ID as the root
     
    .PARAMETER ParentActivityId
    When Provided, This function will include Write-Progress Activities, using this ID as the Parent
     
    .EXAMPLE
    Invoke-TMRecipe -Name 'Migration Recipe' -EventName 'Move 1' -UseWip $True -PublishTasks $True
     
    .OUTPUTS
    None
    #>


    [CmdletBinding()]
    param(        
        [Parameter(Mandatory = $true)]
        [Alias('Recipe')]
        [String]$Name,
        
        [Parameter(Mandatory = $true)]
        [String]$EventName,
        
        [Parameter(Mandatory = $false)]
        [String]$TMSession = 'Default',
        
        [Parameter(Mandatory = $false)]
        [String]$Server = $global:TMSessions[$TMSession].TMServer,
        
        [Parameter(Mandatory = $false)]
        [Bool]$AllowInsecureSSL = $global:TMSessions[$TMSession].AllowInsecureSSL,

        [Parameter(Mandatory = $false)]
        [Switch]$PassThru,
        
        [Parameter(Mandatory = $false)]
        [Switch]$UseWip,
        
        [Parameter(Mandatory = $false)]
        [Switch]$PublishTasks,

        [Parameter(Mandatory = $false)][Int16]$ActivityId,
        [Parameter(Mandatory = $false)][Int16]$ParentActivityId = -1

    )

    begin {
        # Initialize resources
        if (!(Get-Module 'TMD.Common')) {
            Import-Module 'TMD.Common'
        }

        ## Get Session Configuration
        $TMSessionConfig = $global:TMSessions[$TMSession]
        if (-not $TMSessionConfig) {
            Write-Host 'TMSession: [' -NoNewline
            Write-Host $TMSession -ForegroundColor Cyan
            Write-Host '] was not Found. Please use the New-TMSession command.'
            Throw 'TM Session Not Found. Use New-TMSession command before using features.'
        }

        ## Filter out the TM Server Hostname
        $instance = $instance = $Server.Replace('/tdstm', '').Replace('https://', '').Replace('http://', '')

        #Honor SSL Settings
        if ($TMSessionConfig.AllowInsecureSSL) {
            $TMCertSettings = @{SkipCertificateCheck = $true }
        }
        else { 
            $TMCertSettings = @{SkipCertificateCheck = $false }
        }
    }

    process {

        ## Get the Recipe indicated
        $Recipe = Get-TMRecipe -Name $Name -TMSession $TMSession
        if (!$Recipe) {
            throw ("Recipe [$Name] does not exist.")
        }
        
        ## Resolve usage of the UseWip switch
        $FinalUseWip = $UseWip.IsPresent
        if ($UseWip.IsPresent -and !$Recipe.hasWip) {
            
            ## Change to use the Released version
            Write-Host 'Recipe '$Recipe.name' does not have a WIP version. Creating Tasks with the released version instead.'
            $FinalUseWip = $False
        }

        ## Get the required Event
        $TMEvent = Get-TMEvent -Name $EventName
        if (!$TMEvent) {
            New-TMEvent -Name $EventName
        }

        ## Confirm the Recipe and Event
        Write-Host 'Recipe and Event are valid. Generating Tasks...'

        # Update the newly created recipe with the data
        $uri = 'https://'
        $uri += $instance
        $uri += '/tdstm/ws/task/generateTasks'

        ## Create the Post Body
        $PostBody = [PSCustomObject]@{
            recipeId        = $Recipe.recipeId 
            recipeVersionId = $Recipe.recipeVersionId
            deletePrevious  = $true
            useWIP          = $FinalUseWip
            autoPublish     = ($PublishTasks.IsPresent) ?? $False
            eventId         = $TMEvent.id
            tag             = @()  ## TODO: Enable adding tags
        } | ConvertTo-Json -Compress

        ## Set the right content type
        Set-TMHeaderContentType -ContentType 'JSON'
        Set-TMHeaderAccept -Accept 'JSON'

        ## Make the request
        try {
            $response = Invoke-WebRequest -Method Post -Uri $uri -Body $PostBody -WebSession $TMSessionConfig.TMWebSession @TMCertSettings
        }
        catch {
            throw $_
        }

        ## Ensure a useful response came back
        if ($response.StatusCode -eq 200) {
            $responseContent = $response.Content | ConvertFrom-Json
            
            if ($responseContent.status -ne 'success') {
    
                throw ('The recipe could not be run: ' + $responseContent.errors)
            }
        }
        ## Get the Job ID for the Task Generation
        $TaskGenerationJobId = $responseContent.data.jobId
    
        ## With the file uploaded, Initiate the ETL script on the server
        $uri = 'https://'
        $uri += $instance
        $uri += "/tdstm/ws/progress/$TaskGenerationJobId"
                    
        Set-TMHeaderContentType -ContentType JSON -TMSession $TMSession

        ## The Recipe Generation Job has started, monitor the status
        if ($ActivityId) { 
            Write-Progress -Id ($ActivityId + 1) -ParentId $ActivityId -Activity 'Task Generation Started' -CurrentOperation 'Starting ETL Processing' -PercentComplete 5
        }
        else {
            Write-Host 'TransitionManager Task Generation: Starting Generating Tasks'
        }
        
        ## Poll for the status of the Task Generation
        ## TODO: This should be converted to a function for polling the job engine. It's nearly dupilcated now in the Import Batch watching.
        $Completed = $false
        while ($Completed -eq $false) {
            
            ## Check the status of the TaskGeneration Job
            try {
                
                $response = Invoke-WebRequest -Method Get -Uri $uri -WebSession $TMSessionConfig.TMWebSession @TMCertSettings
            }
            catch {
                throw $_.Exception.Message
            }

            ## Check the status of the script
            if ($response.StatusCode -eq 200) {
                $responseContent = $response.Content | ConvertFrom-Json
                if ($responseContent.status -eq 'success') {
                    $TaskGenerationProgress = $responseContent.data
                                    
                    switch ($TaskGenerationProgress.status) {
                        'Queued' { 
                        
                            $CurrentOperation = 'Task Generation Queued'
                            $Status = 'Queued'
                            $ProgressString = 'Status - Queued: ' + $TaskGenerationProgress.percentComp + '%'
                            $PercentComplete = $TaskGenerationProgress.percentComp    
                            $SleepSeconds = 2
                            Break
                        
                        }
                        'Pending' { 
                            $CurrentOperation = 'Task Generation Pending'
                            $Status = 'Pending'
                            $ProgressString = 'Status - Pending: ' + $TaskGenerationProgress.percentComp + '%'
                            $PercentComplete = $TaskGenerationProgress.percentComp    
                            $SleepSeconds = 2
                            Break
                        }
                        'Processing' { 
                            $CurrentOperation = 'Task Generation Running'
                            $Status = 'Generating Tasks'
                            $ProgressString = 'Status - Running: ' + $TaskGenerationProgress.percentComp + '%'
                            $PercentComplete = $TaskGenerationProgress.percentComp    
                            $SleepSeconds = 2    
                            Break
                        }
                        'COMPLETED' {
                            $TaskGenerationJobId = $TaskGenerationProgress.detail
                            $CurrentOperation = 'Task Generation Complete'
                            $Status = 'Task Generation Complete'
                            $SleepSeconds = 0
                            $PercentComplete = 99
                            $ProgressString = 'Status - Task Generation Complete Complete.'
                            $Completed = $true
                            Break
                        }
                        'Failed' {
                            $CurrentOperation = 'Failed'
                            $Status = $TaskGenerationProgress.status
                            Write-Host 'Task Generation Failed '$TaskGenerationProgress.detail
                            Throw $TaskGenerationProgress.detail
                        }
                        Default { 
                            $CurrentOperation = 'State Unknown'
                            $Status = 'Unknown. Sleeping to try again.'
                            $ProgressString = 'Unknown Status: ' + $TaskGenerationProgress.status
                            $PercentComplete = 99
                            $SleepSeconds = 2
                            Break
                        }
                    }
                
                    ## Notify the user of the ETL Progress
                    if ($ActivityId) { 
                        Write-Progress -Id ($ActivityId + 1) `
                            -ParentId $ActivityId `
                            -Activity 'Task Generation' `
                            -CurrentOperation $CurrentOperation `
                            -Status $Status `
                            -PercentComplete $PercentComplete
                    }
                    else {
                        Write-Host $ProgressString
                    }
                }    
            }    

            ## Sleep a few seconds to allow the process to complete
            Start-Sleep -Seconds $SleepSeconds
        }

        ## DEBUGGING
        Write-Host $TaskGenerationJob

    }

    end {

    }
}