lib/Recipes.ps1



# Recipes
Function Get-TMRecipe {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $false)]
        [String]$TMSession = 'Default',

        [Parameter(Mandatory = $false)]
        [String]$Name,

        [Parameter(Mandatory = $false)]
        [Switch]$ResetIDs,

        [Parameter(Mandatory = $false)]
        [String]$SaveCodePath,

        [Parameter(Mandatory = $false)]
        [Switch]$AsJson,

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

    )

    begin {
        # Get the session configuration
        Write-Verbose "Checking for cached TMSession"
        $TMSessionConfig = $global:TMSessions[$TMSession]
        Write-Debug "TMSessionConfig:"
        Write-Debug ($TMSessionConfig | ConvertTo-Json -Depth 5)
        if (-not $TMSessionConfig) {
            throw "TMSession '$TMSession' not found. Use New-TMSession command before using features."
        }
    }
    process {

        # Format the uri
        $uri = "https://$($TMSessionConfig.TMServer)/tdstm/ws/cookbook/recipe/list?archived=n&context=All"
        try {
            $response = Invoke-WebRequest -Method Get -Uri $uri -WebSession $TMSessionConfig.TMWebSession
        }
        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++) {

            ## Get the Recipe in standard format
            $uri = "https://$($TMSessionConfig.TMServer)/tdstm/ws/cookbook/recipe/$($Result[$i].recipeId)"
            try {
                $response = Invoke-WebRequest -Method Get -Uri $uri -WebSession $TMSessionConfig.TMWebSession
            }
            catch {
                return $_
            }
            if ($response.StatusCode -in @(200, 204)) {
                $Result[$i] = ($response.Content | ConvertFrom-Json).data
            }
            else {
                return 'Unable to collect Recipe.'
            }

            ## Get the Recipe in JSON Format
            $uri = "https://$($TMSessionConfig.TMServer)/tdstm/ws/cookbook/recipe/$($Result[$i].recipeId)?format=json"
            try {
                $response = Invoke-WebRequest -Method Get -Uri $uri -WebSession $TMSessionConfig.TMWebSession
            }
            catch {
                return $_
            }

            if ($response.StatusCode -in @(200, 204)) {
                $RecipeData =($response.Content | ConvertFrom-Json).data
                Add-Member -InputObject $Result[$i] -NotePropertyName 'sourceCodeJson' -NotePropertyValue $RecipeData.sourceCode
            }
            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 }
            }
        }

        ## 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

                ##
                ## Save the Recipe (JSON)
                ##
                $RecipeConfigFileName = Join-Path $SaveCodePath "$SafeScriptName.TMRecipe.json"
                $RecipeCodeFileName = Join-Path $SaveCodePath "$SafeScriptName.TMRecipe.groovy"

                ## Save the Source Code
                $Item.sourceCode | Set-Content -Path $RecipeCodeFileName -Force
                $Item.PSObject.Properties.remove('sourceCode')
                $Item | ConvertTo-Json -Depth 10 | Set-Content -Path $RecipeConfigFileName -Force

                # if ($AsJson) {

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

                # ## Write the JSON recipe file
                # Set-Content -Path $JsonScriptPath -Force -Value ($Item | ConvertTo-Json -Depth 100)
                # }

                # else {

                # ##
                # ## Save as a TMRecipe.groovy file
                # ##
                # ## Create a File ame for the Action
                # $GroovyScriptPath = 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 $GroovyScriptPath -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)][Switch]$Update,
        [Parameter(Mandatory = $false)][Switch]$PassThru
    )
    begin {
        # Get the session configuration
        Write-Verbose "Checking for cached TMSession"
        $TMSessionConfig = $global:TMSessions[$TMSession]
        Write-Debug "TMSessionConfig:"
        Write-Debug ($TMSessionConfig | ConvertTo-Json -Depth 5)
        if (-not $TMSessionConfig) {
            throw "TMSession '$TMSession' not found. Use New-TMSession command before using features."
        }

        # Use the TM session if a project id is not provided
        $ProjectId ??= $TMSessionConfig.UserContext.Project.id
    }

    process {

        ## 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 += $TMSessionConfig.TMServer
            $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
            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 -TMSession $TMSession
        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 += $TMSessionConfig.TMServer
        $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
        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 -TMSession $TMSession)
        }
    }
}


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

    ## Handle JSON files
    $File = Get-Item -Path $Path
    if($File.Extension -eq '.json'){

        ## Read the Json file
        $TMRecipe = Get-Content -Path $Path | ConvertFrom-Json

        ## This might be a JSON+Groovy pair
        $RecipeGroovyPath = $Path -Replace '.TMRecipe.json', '.TMRecipe.groovy'
        if (Test-Path $RecipeGroovyPath) {
            Add-Member -InputObject $TMRecipe -NotePropertyName sourceCode -NotePropertyValue ((Get-Content -Path $RecipeGroovyPath -Raw).trim())
        }

        ## Remove JSON metadata that is only stored offline
        if($TMRecipe.PSObject.Properties.Name -contains 'sourceCodeJson'){
            $TMRecipe.PSObject.Properties.Remove('sourceCodeJson')
        }

        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://$($TMSessionConfig.TMServer)/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
# 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[]]$Tags,

        [Parameter(Mandatory = $false)]
        [String]$TMSession = 'Default',

        [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 {

        ## 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.'
        }
    }

    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-Verbose '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
        }

        ## Find any associated tags
        $IncludeTags = Get-TMTag -TMSession $TMSession | Where-Object {
            $_.name -in $Tags
        }

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

        # Update the newly created recipe with the data
        $uri = 'https://'
        $uri += $TMSessionConfig.TMServer
        $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             = $IncludeTags.id -as [array]
        } | 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
        }
        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 Datascript on the server
        $uri = 'https://'
        $uri += $TMSessionConfig.TMServer
        $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 Datascript Processing' -PercentComplete 5
        }
        else {
            Write-Verbose '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
            }
            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 Datascript 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

    }
}