Public/ConnectorState.ps1

<#
.SYNOPSIS
    Enables a Keepit connector by clearing the disable_backup attribute
.DESCRIPTION
    Enables a Keepit connector by removing the disable_backup attribute, allowing backup
    jobs to run on the connector. If the connector is already enabled (no disable_backup
    attribute), the cmdlet succeeds without making changes.

    Supports pipeline input from Get-KeepitConnector for bulk operations.
.PARAMETER Connector
    The connector name or GUID. Can be piped from Get-KeepitConnector.
    Aliases: ConnectorGuid, Name
.EXAMPLE
    Enable-KeepitConnector -Connector "abc123-def456"

    Enables the connector with the specified GUID.
.EXAMPLE
    Enable-KeepitConnector -Connector "Production M365"

    Enables the connector by name.
.EXAMPLE
    Get-KeepitConnector | Where-Object { $_.Name -like "*Test*" } | Enable-KeepitConnector

    Enables all connectors matching the name pattern.
.OUTPUTS
    PSCustomObject with properties:
        - ConnectorGuid: The connector GUID (lowercase)
        - Name: The connector name
        - Enabled: Boolean indicating the connector is now enabled ($true)
        - Status: "Success" or error message
.NOTES
    Requires an active connection via Connect-KeepitService.
    Enabling an already-enabled connector is a no-op and returns success.

    API endpoint used:
    - DELETE /users/{userId}/devices/{connectorGUID}/attributes/disable_backup
#>

function Enable-KeepitConnector {
    [CmdletBinding(SupportsShouldProcess)]
    [OutputType([PSCustomObject])]
    param(
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [Alias('ConnectorGuid', 'Name')]
        [string]$Connector
    )

    begin {
        Write-Verbose "Enable-KeepitConnector: Initializing"

        # Get authentication header and base URL once for all pipeline items
        try {
            $authHeader = Get-AuthHeader
            $baseUrl = Get-KeepitBaseUrl
            $userId = Get-KeepitUserId -AuthHeader $authHeader -BaseUrl $baseUrl
            Write-Verbose "Base URL: $baseUrl, User ID: $userId"
        }
        catch {
            throw
        }
    }

    process {
        try {
            # Resolve connector identity to GUID
            $resolved = Resolve-KeepitConnectorIdentity -Identity $Connector
            $connectorGuid = $resolved.ConnectorGuid
            $connectorName = $resolved.Name
            Write-Verbose "Connector: $connectorName ($connectorGuid)"

            # Check if disable_backup attribute exists
            $attrUri = "$baseUrl/users/$userId/devices/$connectorGuid/attributes/disable_backup"
            $headers = @{
                'Authorization' = $authHeader
            }

            $attributeExists = $false
            try {
                $null = Invoke-WebRequest -Uri $attrUri -Method Get -Headers $headers -ErrorAction Stop
                $attributeExists = $true
                Write-Verbose "disable_backup attribute exists, will delete it"
            }
            catch {
                # Attribute doesn't exist - connector is already enabled
                Write-Verbose "disable_backup attribute not found - connector is already enabled"
            }

            if ($PSCmdlet.ShouldProcess($connectorName, 'Enable connector')) {
                # Delete the attribute if it exists
                if ($attributeExists) {
                    Write-Verbose "Deleting disable_backup attribute"
                    try {
                        Invoke-RestMethod -Uri $attrUri -Method Delete -Headers $headers -ErrorAction Stop
                        Write-Verbose "Successfully deleted disable_backup attribute"
                    }
                    catch {
                        $PSCmdlet.ThrowTerminatingError(
                            [System.Management.Automation.ErrorRecord]::new(
                                [System.Exception]::new("Failed to delete disable_backup attribute: $($_.Exception.Message)", $_.Exception),
                                'KeepitApiError',
                                [System.Management.Automation.ErrorCategory]::WriteError,
                                $connectorGuid
                            )
                        )
                    }
                }

                # Return result object
                [PSCustomObject]@{
                    ConnectorGuid = $connectorGuid
                    Name          = $connectorName
                    Enabled       = $true
                    Status        = 'Success'
                }
            }
        }
        catch {
            Write-Error "Failed to enable connector '$Connector': $($_.Exception.Message)"

            [PSCustomObject]@{
                ConnectorGuid = if ($connectorGuid) { $connectorGuid } else { $Connector }
                Name          = if ($connectorName) { $connectorName } else { $Connector }
                Enabled       = $null
                Status        = $_.Exception.Message
            }
        }
    }
}

<#
.SYNOPSIS
    Disables a Keepit connector by setting the disable_backup attribute
.DESCRIPTION
    Disables a Keepit connector by setting the disable_backup attribute to TRUE,
    preventing backup jobs from running on the connector. If the connector is already
    disabled (disable_backup attribute exists), the cmdlet succeeds without making changes.

    Supports pipeline input from Get-KeepitConnector for bulk operations.
.PARAMETER Connector
    The connector name or GUID. Can be piped from Get-KeepitConnector.
    Aliases: ConnectorGuid, Name
.EXAMPLE
    Disable-KeepitConnector -Connector "abc123-def456"

    Disables the connector with the specified GUID.
.EXAMPLE
    Disable-KeepitConnector -Connector "Test Connector"

    Disables the connector by name.
.EXAMPLE
    Get-KeepitConnector | Where-Object { $_.Name -like "*Test*" } | Disable-KeepitConnector

    Disables all connectors matching the name pattern.
.OUTPUTS
    PSCustomObject with properties:
        - ConnectorGuid: The connector GUID (lowercase)
        - Name: The connector name
        - Enabled: Boolean indicating the connector is now disabled ($false)
        - Status: "Success" or error message
.NOTES
    Requires an active connection via Connect-KeepitService.
    Disabling an already-disabled connector is a no-op and returns success.
    Active backup jobs may continue running but will not be rescheduled.

    API endpoint used:
    - PUT /users/{userId}/devices/{connectorGUID}/attributes/disable_backup
#>

function Disable-KeepitConnector {
    [CmdletBinding(SupportsShouldProcess)]
    [OutputType([PSCustomObject])]
    param(
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [Alias('ConnectorGuid', 'Name')]
        [string]$Connector
    )

    begin {
        Write-Verbose "Disable-KeepitConnector: Initializing"

        # Get authentication header and base URL once for all pipeline items
        try {
            $authHeader = Get-AuthHeader
            $baseUrl = Get-KeepitBaseUrl
            $userId = Get-KeepitUserId -AuthHeader $authHeader -BaseUrl $baseUrl
            Write-Verbose "Base URL: $baseUrl, User ID: $userId"
        }
        catch {
            throw
        }
    }

    process {
        try {
            # Resolve connector identity to GUID
            $resolved = Resolve-KeepitConnectorIdentity -Identity $Connector
            $connectorGuid = $resolved.ConnectorGuid
            $connectorName = $resolved.Name
            Write-Verbose "Connector: $connectorName ($connectorGuid)"

            # Check if disable_backup attribute exists
            $attrUri = "$baseUrl/users/$userId/devices/$connectorGuid/attributes/disable_backup"
            $headers = @{
                'Authorization' = $authHeader
            }

            $attributeExists = $false
            try {
                $null = Invoke-WebRequest -Uri $attrUri -Method Get -Headers $headers -ErrorAction Stop
                $attributeExists = $true
                Write-Verbose "disable_backup attribute already exists - connector is already disabled"
            }
            catch {
                # Attribute doesn't exist - need to create it
                Write-Verbose "disable_backup attribute not found - will create it"
            }

            if ($PSCmdlet.ShouldProcess($connectorName, 'Disable connector')) {
                # Set the attribute if it doesn't exist
                if (-not $attributeExists) {
                    Write-Verbose "Setting disable_backup attribute to 1"
                    $putHeaders = @{
                        'Authorization' = $authHeader
                        'Content-Type'  = 'application/octet-stream'
                    }

                    try {
                        $body = [System.Text.Encoding]::UTF8.GetBytes("1")
                        Invoke-RestMethod -Uri $attrUri -Method Put -Headers $putHeaders -Body $body -ErrorAction Stop
                        Write-Verbose "Successfully set disable_backup attribute"
                    }
                    catch {
                        $PSCmdlet.ThrowTerminatingError(
                            [System.Management.Automation.ErrorRecord]::new(
                                [System.Exception]::new("Failed to set disable_backup attribute: $($_.Exception.Message)", $_.Exception),
                                'KeepitApiError',
                                [System.Management.Automation.ErrorCategory]::WriteError,
                                $connectorGuid
                            )
                        )
                    }
                }

                # Return result object
                [PSCustomObject]@{
                    ConnectorGuid = $connectorGuid
                    Name          = $connectorName
                    Enabled       = $false
                    Status        = 'Success'
                }
            }
        }
        catch {
            Write-Error "Failed to disable connector '$Connector': $($_.Exception.Message)"

            [PSCustomObject]@{
                ConnectorGuid = if ($connectorGuid) { $connectorGuid } else { $Connector }
                Name          = if ($connectorName) { $connectorName } else { $Connector }
                Enabled       = $null
                Status        = $_.Exception.Message
            }
        }
    }
}