OctopusVariables.psm1

Import-Module PowershellOctopusClientPS
(Get-Module -ListAvailable PowershellOctopusClientPS).ModuleBase

$octoclientpath = Join-Path -Path (Get-Module -ListAvailable PowershellOctopusClientPS).ModuleBase -ChildPath "lib\Octopus.Client.dll"
$newtonsoftPath = Join-Path -Path (Get-Module -ListAvailable PowershellOctopusClientPS).ModuleBase -ChildPath "lib\Newtonsoft.Json.dll"

try
{
    Add-Type -Path $newtonsoftPath
    Add-Type -Path $octoclientpath
}
catch [System.Reflection.ReflectionTypeLoadException]
{    #system.attonations always throws
    #Write-Host "Message: $($_.Exception.Message)"
    #Write-Host "StackTrace: $($_.Exception.StackTrace)"
    #Write-Host "LoaderExceptions: $($_.Exception.LoaderExceptions)"
}
<#
    .SYNOPSIS
    return a setup client
#>

function LoadOctopusClientAndDependancies {
[OutputType([Octopus.Client.OctopusClient])]
Param(
        [parameter(Mandatory=$true)][String] $url,
        [parameter(Mandatory=$true)][String] $apiKey
    )
    
    $client = [Octopus.Client.OctopusClient]::new([Octopus.Client.OctopusServerEndpoint]::new($url, $apiKey))
    $client
}

function SetProjectVariableInEnviromentScope {
    Write-Output "TODO: SetProjectVariableInEnviromentScope!"
}

<#
#>

function CreateVariableInSetWithValueAndEnviromentScope
{
    Param(
        [parameter(Mandatory=$true)][String] $octopusURL,
        [parameter(Mandatory=$true)][String] $octopusAPIKey,
        [parameter(Mandatory=$true)][String] $enviromentScope,
        [parameter(Mandatory=$true)][String] $space,
        [parameter(Mandatory=$true)][String] $variableSet,
        [parameter(Mandatory=$true)][String] $variableName,
        [parameter(Mandatory=$true)][String] $variableValue
    )

    $client = LoadOctopusClientAndDependancies -url $octopusURL -apiKey $octopusAPIKey   
    $repository = $client.ForSystem()    
    $spaceResource = $repository.Spaces.FindByName($space)
    $repositoryForSpace = $client.ForSpace($spaceResource)
    $theEnviromentResource = $repositoryForSpace.Environments.FindByName($enviromentScope)
    $vSetResource = $repositoryForSpace.LibraryVariableSets.CreateOrModify($variableSet)

    $variables | foreach {
        $hashVar = $_
        $alreadyExists = $false
        $vSetResource.Variables.Instance.Variables | foreach {
            $currVar = $_
            if($currVar.Name -eq $variableName){
                if($currVar.Scope.ContainsKey('Environment')) {
                    if($_.Scope['Environment'].Contains($theEnviromentResource.Id) -eq $true) { 
                        $alreadyExists = $true
                    } 
                }
            }
        }
        if($alreadyExists -eq $true) { 
            Write-Output "The variable $variableName already exists with an enviroment scope in $($theEnviromentResource.Name). This process will NOT update the value."
        }else {
            $scopeSpec = [Octopus.Client.Model.ScopeSpecification]::new()
            $scopeSpec.Add("Environment",[Octopus.Client.Model.ScopeValue]::new($theEnviromentResource.Id))
            $newVar = [Octopus.Client.Model.VariableResource]::new()
            $newVar.Description = 'Created by CreateVariableInSetWithValueAndEnviromentScope automation.'
            $newVar.Scope = $scopeSpec
            $newVar.Name  = $variableName
            $newVar.Value = $variableValue
            $newVar.IsSensitive = $false        
            $vSetResource.Variables.Instance.Variables.Add($newVar)
            $vSetResource.Variables.Save() | Out-Null   
            Write-Output "Created new value in VariableSet: $($vSetResource.Instance.Name) for Variable: $variableName with Value: $variableValue Scoped to Enviroment: $($theEnviromentResource.Name)"
        }
    }
}