Public/SC_Common.ps1

<#
.SYNOPSIS
    Detects the SEPPMAIL.Cloud deployment status, based in M365 Tenant information
.DESCRIPTION
    Checks deployment Status of the SEPPMAIL.Cloud based on M365 tenant information from outside, based on DNS information
     
    - Queries routing mode based on available MX records in the SEPPMAIL.cloud
    - Queries region based on IP addresses and mail hosts
    - Tests if MX record is set correctly in Inline Mode
    - Checks if the SEPPMAIL.cloud is prepared for Certificate-based-Connectors
     
    Creates a PSObject with the following values:
     
    Routing = inline/parallel # Routing Mode
    Region = ch/de/prv # Cloud Region (data center location)
    SEPPMAILCloudDomain = 'contoso.de','contoso.ch' # Mail domains which will be routed via SEPPMAIL. Is basis for naming the mail routing hosts (gate/relay/mail)
    CBCenabled = $true/$false # Certificate Based Connectors setup available
    CBCConnectorHost = '<tenantid>.<rg>.seppmail.cloud' # Hostname of TLS host for CBC
    InlineMXMatch = $true/$false # (Inline Mod only) MX record points to the correct (SEPPMAIL) host
    RelayHost = domain-tls.relay.seppmail.cloud # Name of relay host
    GateHost = domain-tls.gate.seppmail.cloud # Name of gate host
    MailHost = domain-tls.mail.seppmail.cloud # Name of mail host
.PARAMETER SEPPMAILCloudDomain
    Accepted domain booked for cloud onboarding. If omitted, the cached tenant
    default accepted domain is used. Requires an Exchange Online connection and DNS
    access. Although the parameter accepts an array, the current implementation
    reports on the last supplied domain; call separately for each domain.
 
.NOTES
    Emits parameters for New-SC365Setup
.LINK
    https://github.com/seppmail/SEPPMAIL365cloud/blob/main/README.md
.EXAMPLE
    Get-SC365DeploymentInfo
 
    DeployMentStatus : True
    SEPPMAILCloudDomain : contoso.com
    Region : ch
    Routing : inline
    InBoundOnly : False
    CBCDeployed : True
    CBCConnectorHost : 271dd771-832d-4913-80d7-9c21616accd4.ch.seppmail.cloud
    CBCDnsEntry : c60abc9d247a2bf21cbc3344eef199eb738876b2.cbc.seppmail.cloud
    InlineMXMatch : True
    MailHost :
    RelayHost : contoso-com.relay.seppmail.cloud
    GateHost : contoso-com.gate.seppmail.cloud
.EXAMPLE
    Get-SC365DeploymentInfo -SEPPMAILCLoudDomain contoso.eu
 
    DeployMentStatus : True
    SEPPMAILCloudDomain : contoso.eu
    Region : de
    Routing : inline
    InBoundOnly : False
    CBCDeployed : True
    CBCConnectorHost : 271dd771-832d-4913-80d7-9c21616accd4.de.seppmail.cloud
    CBCDnsEntry : c60abc9d247a2bf21cbc3344eef199eb738876b2.cbc.seppmail.cloud
    InlineMXMatch : True
    MailHost :
    RelayHost : contoso-eu.relay.seppmail.cloud
    GateHost : contoso-eu.gate.seppmail.cloud
.EXAMPLE
    Get-SC365DeploymentInfo -SEPPMAILCloudDomain contoso.ch
 
    Checks the deployment status for domain contoso.ch in parallel routing mode.
    Displays details about Mail-Host, Region (ch) and CBC configuration.
.EXAMPLE
    @('contoso.eu', 'contoso.ch') | ForEach-Object { Get-SC365DeploymentInfo -SEPPMAILCloudDomain $_ }
 
    Performs a separate deployment check for each accepted domain.
 
#>

function Get-SC365DeploymentInfo {
    [CmdletBinding()]
    param (
        [Parameter(   
            Mandatory   = $false,
            HelpMessage = "Domain name you selected for Tenant-onboarding"
         )]
         [string[]]$SEPPMAILCloudDomain
    )
    
    begin {
        if (!(Test-SC365ExoConnStatus)){
            throw [System.Exception] "You're not connected to Exchange Online - please connect to the designated tenant prior to using this CmdLet" }
        else {
            Write-Information "Connected to Exchange Organization `"$Script:ExODefaultDomain`"" -InformationAction Continue
        }
        # Reset the Stage
        $DeployMentStatus = $null
        $region = $null
        $routing = $null
        $inBoundOnly = $null

        $DeploymentInfo = [PSCustomObject]@{
            DeploymentStatus    = $null
            SEPPMAILCloudDomain = $Null
            Region              = $null
            Routing             = $null
            InboundOnly         = $null
            CBCDeployed         = $Null
            CBCConnectorHost    = $null
            CBCDnsEntry         = $null
            InlineMXMatch       = $null
            MailHost            = $null
            GateHost            = $null
            RelayHost           = $null
            SwissSignCheckTXT   = $null
            spfTXT              = $null
            DnsSecurEmailCNAME  = $null
            DnsLetsEncryptCNAME = $null
            DnsDKIMTXT          = $null
            DnsWildCardActive   = $null
        }
    }
    
    process {
        #region Select DefaultDomain
            if (!($SEPPMAILCloudDomain)) {
                [String]$DNSHostDomain = $tenantAcceptedDomains |Where-Object 'Default' -eq $true |select-Object -ExpandProperty DomainName
                Write-Verbose "Extracted Default-Domain with name $DNSHostDomain from TenantDefaultDomains"
                }
            else {
                foreach ($dom in $SEPPMAILCloudDomain) {
                    if (!($tenantAcceptedDomains.DomainName.Contains($Dom))) {
                        throw [System.Exception] "Domain $Dom is not member of this tenant! Check for typos or connect to different tenant"
                    }
                    else {
                        Write-Verbose "Domain $Dom is member of the tenant domains"
                        if ($dom -eq ($tenantAcceptedDomains |Where-Object 'Default' -eq $true |select-Object -ExpandProperty DomainName)) {
                            $DnsHostDomain = $dom
                        }
                        else {
                            Write-Verbose "TenantDefaultDomain not selected, using $dom and DNSHost domain"
                            $DnsHostDomain = $dom
                        }
                    }
                }
            }

        #endregion Select DefaultDomain

        #region Query SEPPMAIL routing-Hosts DNS records and detect routing mode and in/outbound
            [string]$relayHost = $DnsHostDomain.Replace('.','-') + '.relay.seppmail.cloud'
            Write-Verbose "Created RelayHost $relayHost"
             [string]$mailHost = $DnsHostDomain.Replace('.','-') + '.mail.seppmail.cloud'
             Write-Verbose "Created MailHost $mailHost"
             [string]$gateHost = $DnsHostDomain.Replace('.','-') + '.gate.seppmail.cloud'
             Write-Verbose "Created GateHost $gateHost"
        
        $defEAPref = $ErrorActionPreference
        $ErrorActionPreference = 'SilentlyContinue'

        $DeploymentStatus = 'unknown'
        if (((Resolve-Dns -Query $gateHost).Answers)) {
            $routing = 'inline'
            Write-Verbose "$gateHost alive ==> Inline"
            if ((Resolve-Dns -Query $relayHost).Answers) {                    
                $inBoundOnly = $false
                Write-Verbose "$gateHost and $relayHost alive ==> InLine-bidirectional"
                $deploymentStatus = $true                
            } else {
                if (!((Resolve-Dns -Query $relayHost).Answers)) {
                    $inBoundOnly = $true
                    $relayHost = $null
                    Write-Verbose "$gateHost alive,$relayHost missing ==> InLine-InBound only"
                    $deploymentStatus = $true                
                }
            }
        }
        else {
            if ((Resolve-Dns -Query $mailHost ).Answers) {
                Write-Verbose "$mailHost alive ==> parallel"
                $routing = 'parallel'
                $deploymentStatus = $true                
            } else {
                $mailHost = $null
                $deploymentStatus = $false
            }            
        }
        #endregion mail host queries

        #region DoubleCheck if MX Record is set correctly
        $mxFull = get-mxrecordreport -Domain $DnsHostDomain
        $mxFullVerbose = $mxFull | foreach-object {"$($_.HighestPriorityMailHost) $($_.HighestpriorityMailhostIPAddress)"}
        Write-Verbose "MXFull record is $mxFullVerbose"
            
        if ($mxFull.Count -eq 0) {
            $DeployMentStatus = $false
        }
        else {
            if ($mxFull.Count -eq 1) {
                $mx = $mxFull | Select-Object -ExpandProperty highestpriorityMailHost -Unique
            } 
            if ($mxFull.Count -gt 1) {
                $mx = $mxFull[0] | Select-Object -ExpandProperty highestpriorityMailHost -Unique
            }
                
            if (($mx.Split($DnsHostDomain.Replace('.', '-'))) -eq '.gate.seppmail.cloud') {
                Write-Verbose "MX = SEPPMAIL"
            }
            if (($mx.Split($DnsHostDomain.Replace('.', '-'))) -eq '.mail.protection.outlook.com') {
                Write-Verbose "MX = Microsoft"
            }
            if ($routing -eq 'inline') {
                if ($mx -eq $gateHost) {
                    Write-Verbose "MX record $mx in M365 Config matches $gateHost"
                    $mxMatch = $true
                }
                else {
                    Write-Warning "MX Record $mx configured in M365 does not fit to SEPPMAIL GateHost $gateHost in DNS - Check your provisioning Status in SEPPMAIL.cloud Portal"
                    $mxMatch = $false
                    $DeployMentStatus = $false
                }
            }   
        }
        #endRegion MX Check

        #region Identify region based on Cloud-IPAddresses
            $region = $null
             $ch = Get-SC365CloudConfig -region 'ch'
             $de = Get-SC365CloudConfig -region 'de'
            $prv = Get-SC365CloudConfig -region 'prv'
            $dev = Get-SC365CloudConfig -region 'dev'
            if ($routing -eq 'inline') {
                [String[]]$GateIP = ((Resolve-Dns -Query $GateHost).Answers)|Select-Object -expand Address| Select-Object -expand IPAddressToString
                 Foreach ($IP in $GateIP) {if ($ch.IPv4GateIPs.Contains($Ip)) {$region = 'ch';break}}
                 Foreach ($IP in $GateIP) {if ($de.IPv4GateIPs.Contains($Ip)) {$region = 'de';break}}
                Foreach ($IP in $GateIP) {if ($prv.IPv4GateIPs.Contains($Ip)) {$region = 'prv';break}}
                Foreach ($IP in $GateIP) {if ($dev.IPv4GateIPs.Contains($Ip)) {$region = 'dev';break}}
            }
            if ($routing -eq 'parallel') {
                [string[]]$MailIP = ((Resolve-Dns -Query $MailHost).Answers)|Select-Object -expand Address| Select-Object -expand IPAddressToString
                 Foreach ($ip in $mailIp) {if ($ch.IPv4MailIPs.Contains($Ip)) { $region = 'ch';break}}
                 Foreach ($ip in $mailIp) {if ($de.IPv4MailIPs.Contains($Ip)) { $region = 'de';break}}
                Foreach ($ip in $mailIp) {if ($prv.IPv4MailIPs.Contains($IP)) { $region = 'prv';break}}
                Foreach ($ip in $mailIp) {if ($dev.IPv4MailIPs.Contains($IP)) { $region = 'dev';break}}
            }
        #endregion Cloud-IP-Addresses

        #region Check CBC Availability
            [String]$TenantID = Get-SC365TenantID -MailDomain $DnsHostDomain -OutVariable "TenantID"
            Write-Verbose "TenantID = $TenantID"
            $TenantIDHash = Get-SC365StringHash -String $TenantID
            [string]$hashedDomain =  $TenantIDHash + '.cbc.seppmail.cloud'
            Write-Verbose "hashedDomain = $hashedDomain"
            if (((resolve-dns -query $hashedDomain -QueryType TXT).Answers)) {
               $CBCDeployed = $true
               Write-Verbose "$HashedDomain of TenantID $tenantId has a CBC entry"
            } else {
               $CBCDeployed = $false
               Write-Warning "Could not find TXT Entry for TenantID $TenantID of domain $DNSHostCloudDomain. Setup will most likely fail! Go to the SEPPMAIL.cloud-portal and check the deployment status."
            }
        #endregion CBC
        
        #region Advanced DNS Queries
        
        # TXT records (Swisssign check and SPF)
        $txtRecords = (Resolve-dns -querytype TXT $DNSHostdomain).Answers
        if ($txtRecords) { 
            $swisssignTXTRecord = $txtRecords|Where-Object EscapedText -like 'swisssign-check*'
            Write-verbose "SwissSignTXT Record = $swissSignTXTRecord"
            if ($swissSignTXTRecord) {
                $swissSignCheck = $swissSignTXTRecord.EscapedText.Trim('{','}')
            }
            else {
                Write-Warning "Swisssign TXT (swissSign-check) record is missing - SC-CERT deployment will fail!"
            }
            $spfTXTrecord = $txtRecords|Where-Object EscapedText -like 'v=spf*'
            Write-Verbose "spfTXT Record = $spfTXTrecord"
            if ($spfTXTrecord) {
                $spf = $spfTXTrecord.EscapedText.Trim('{','}')
            }
            else {
                Write-Warning "SPF TXT (v=spf*) record is missing"
            }
        }

        ## WebService hosts
        [String]$SecurEmailCNAME = (Resolve-dns -querytype CNAME -Query ('securemail.' + $DNSHostdomain)).Answers.CanonicalName.Value
        Write-Verbose "Securemail CNAME = $SecurEmailCNAME"
        ## Letsencrypt
        [String]$LetsEncryptCNAME = (Resolve-dns -querytype CNAME -Query ('_acme-challenge.securemail.' + $DNSHostdomain)).Answers.CanonicalName.Value
        Write-Verbose "LetsEncrypt CNAME = $LetsEncryptCNAME"

        ## DKIM (default._domainkey)
        [String]$dkimRecord = (resolve-dns -QueryType TXT -query ('default._domainkey.' + $DNSHostDomain)).Answers.EscapedText
        Write-Verbose "DKIM record = $dkimrecord"
        <# Wildcard recordscheck
        Der Code-Block soll prüfen, ob für die Domain ein DNS-Wildcard-Record (*.example.com) konfiguriert ist:
        Die Idee dahinter ist ein klassischer Wildcard-Detection-Trick:
 
        Man fragt einen absichtlich unsinnigen, nicht existierenden Subdomain-Namen ab.
        Kommt trotzdem eine Antwort zurück, muss ein Wildcard-Record vorliegen, der jeden beliebigen Subdomain-Namen auflöst.
        Kommt keine Antwort → kein Wildcard vorhanden.
        #>

        if ((resolve-dns -query ('jioak84-nlkjec.' + $DNSHostDomain)).Answers.EscapedText) {
            $WildcardRecord = $true
        }
        else {
            $WildcardRecord = $false
        }
        $ErrorActionPreference = $defEAPref
        #endregion
    }
    end {
                          $DeploymentInfo.DeploymentStatus = $DeploymentStatus
                                    $DeploymentInfo.Region = $region
                                   $DeploymentInfo.Routing = $routing
                              $DeploymentInfo.InboundOnly  = $inBoundOnly
                       $DeploymentInfo.SEPPMAILCloudDomain = $DNSHostDomain
                               $DeploymentInfo.CBCDeployed = $CBCDeployed
                                               if ($region) {$DeploymentInfo.CBCConnectorHost = ($tenantId + ((Get-Variable $region).Value.TlsCertificate).Replace('*',''))}
                                if ($CBCDeployed -eq $true) {$DeploymentInfo.CBCDnsEntry = ($TenantIDHash + '.cbc.seppmail.cloud')}
                                 if ($routing -eq 'inline') {$DeploymentInfo.InlineMXMatch = $MxMatch}
        if (($routing -eq 'inline') -and (!($inBoundOnly))) {$DeploymentInfo.RelayHost = $relayHost}
                                 if ($routing -eq 'inline') {$DeploymentInfo.GateHost = $gateHost}
                               if ($routing -eq 'parallel') {$DeploymentInfo.MailHost = $MailHost}
        # DNS Records
                         $DeploymentInfo.swisssignCheckTXT = $swisssignCheck
                                    $DeploymentInfo.spfTXT = $spf
                        $DeploymentInfo.DnsSecurEmailCNAME = $SecurEmailCNAME
                       $DeploymentInfo.DnsLetsEncryptCNAME = $LetsEncryptCNAME
                                $DeploymentInfo.DnsDKIMTXT = $DKIMRecord
                         $DeploymentInfo.DnsWildCardActive = $wildcardRecord
        return $DeploymentInfo
    }
}

<#
.SYNOPSIS
    Removes all Rules and Connectors
.DESCRIPTION
    Based on autodiscovery, or forced values through parameters, Remove-SC365Setup removes all connectors and rules from an Exo-Tenant
.PARAMETER routing
    Optional routing mode: parallel (p) or inline (i). Discovery can replace this
    value: the implementation performs discovery unless both routing and InBoundOnly
    are supplied with InBoundOnly enabled. Review discovered values before removal.
.PARAMETER InBoundOnly
    Available in the inline parameter set. When enabled, skip transport rule removal
    and remove only the inbound connector. Otherwise remove rules and both connectors.
    Discovery can also set this switch based on the provisioned cloud deployment.
.PARAMETER WhatIf
    Passed through to nested ShouldProcess-aware removal commands via PowerShell's
    preference handling. Discovery and reads still run. The wrapper does not have
    its own ShouldProcess gate and can print completion messages during a preview.
.PARAMETER Confirm
    Controls confirmations in nested removal commands. -Confirm:$false suppresses
    ShouldProcess confirmations; this wrapper has no separate confirmation gate.
.NOTES
    - none -
.LINK
    https://github.com/seppmail/seppmail365cloud
.EXAMPLE
    Remove-SC365Setup
     
    Automatically removes all SEPPMAIL.cloud Rules and Connectors in discovery mode.
    The routing mode (inline/parallel) is detected automatically.
.EXAMPLE
    Remove-SC365Setup -routing parallel
     
    Requests parallel setup removal. Discovery may replace the supplied routing value.
    Removes Inbound and Outbound Connectors as well as Transport Rules.
.EXAMPLE
    Remove-SC365Setup -routing inline
     
    Requests inline setup removal. Discovery may replace the supplied routing value.
    MX records should be reset to Microsoft after removal.
.EXAMPLE
    Remove-SC365Setup -routing inline -InboundOnly
     
    Removes an inline configuration in "InboundOnly" mode.
    Only Inbound Connectors are removed, no Outbound Rules.
.EXAMPLE
    Remove-SC365Setup -WhatIf
     
    Shows what changes would be made without actually executing them.
    Useful for verification before actual removal.
.EXAMPLE
    Remove-SC365Setup -routing inline -InboundOnly -Confirm
 
    Skips discovery and requests confirmation for removal of the inline inbound connector.
    Transport rules and the outbound connector are retained.
#>

function Remove-SC365Setup {
    [CmdletBinding(
        SupportsShouldProcess = $true,
        ConfirmImpact = 'Medium',
        DefaultParameterSetName='parallel'
        )]
    
    param(
        [Parameter(
            ParameterSetName = 'parallel',
            Mandatory=$false,
            HelpMessage="Inline routing via SEPPMAIL (MX ==> SEPPMAIL), or routing via Microsoft (MX ==> Microsoft)"
            )]
            [ValidateNotNullOrEmpty()]
            [ValidateSet('parallel','inline','p','i')]
        [Parameter(
            ParameterSetName = 'inline',
            Mandatory=$false,
            HelpMessage="Inline routing via SEPPMAIL (MX ==> SEPPMAIL), or routing via Microsoft (MX ==> Microsoft)"
            )]
            [ValidateNotNullOrEmpty()]
            [ValidateSet('parallel','inline','p','i')]
        [String]$routing,

        [Parameter(
            ParameterSetName = 'inline',
            Mandatory=$false,
            HelpMessage="No routing of outbound traffic via SEPPMAIL.cloud"
            )]
        [switch]$InBoundOnly
    )
    Begin {
        if(!(Test-SC365ConnectionStatus)) {
            throw [System.Exception] "You're not connected to Exchange Online - please connect prior to using this CmdLet"        
        }
        else {
            if ((!($InboundOnly)) -or (!($routing)) ) {
                try {
                    $deploymentInfo = Get-SC365DeploymentInfo
                } catch {
                    Throw [System.Exception] "Could not autodetect SEPPMAIL.cloud Deployment Status, use manual parameters"
                }
                if ($DeploymentInfo.DeployMentStatus -eq $false) {
                    Write-Error "SEPPMAIL.cloud setup not (fully) deployed. Use Cloud-Portal and fix deployment."
                    break
                } 
                else {
                    if ($DeploymentInfo) {
                                       if ($deploymentInfo.Routing) {$Routing = $deploymentInfo.Routing} else {Write-Error "Cloud not autodetect routing info, use manual parameters"; break}
                         if ($DeploymentInfo.inBoundOnly -eq $true) {$inboundOnly = $true}
                        if ($DeploymentInfo.inBoundOnly -eq $false) {$inboundOnly = $false}
                         if ($null -eq $DeploymentInfo.inBoundOnly) {$inboundOnly = $false}
                    }
                }
            } 
            else {
                if ($deploymentInfo.routing -eq 'p') {$routing = 'parallel'}
                if ($deploymentInfo.routing -eq 'i') {$routing = 'inline'}
            }
        }
    }
    Process {
        Write-Verbose "Creating Progress Bar"
        $objectCount = $null
        # Count Rules
        foreach ($file in (Get-ChildItem -Path "$psscriptroot\..\ExOConfig\SC_Rules\")) {
            $objectCount += if ((Get-SC365TransportRuleSettings -routing $routing -file $file).count -gt 0) {1}
        }

        # Count Connectors
        #if ((Get-SC365InboundConnectorSettings -routing $routing -file $file).count -gt 0) {1}
        $objectCount += 2

        try {
            if ($InBoundOnly) {
                #Write-Progress -Activity "Removing SEPPMAIL.Cloud Setup" -Status "Removing Rules" -PercentComplete (0)
                Write-Information '--- Remove connector(s) ---' -InformationAction Continue
                Remove-SC365Connectors -routing $routing -InboundOnly:$inboundOnly
            }
            else {
                #Write-Progress -Activity "Removing SEPPMAIL.Cloud Setup" -Status "Removing Rules" -PercentComplete (0)
                Write-Information '--- Removing transport rules ---' -InformationAction Continue
                Remove-SC365Rules
                Write-Information '--- Remove connector(s) ---' -InformationAction Continue
                Remove-SC365Connectors -routing $routing -InboundOnly:$inboundOnly
            }
        } catch {
            throw [System.Exception] "Error: $($_.Exception.Message)"
            break
        }
    }
    End{
        Write-Information "--- Successfully removed SEPPMAIL.cloud Setup in $routing mode ---" -InformationAction Continue

    }
}

<#
.SYNOPSIS
    Creates all Rules and Connectors for SEPPMAIL.cloud
.DESCRIPTION
    Based on autodiscovery, or forced values through parameters, New-SC365Setup creates all connectors and rules for an Exo-Tenant
.PARAMETER SEPPMAILCloudDomain
    Accepted domain or array of domains booked for SEPPMAIL.cloud. Alias: domain.
    If any of domain, region or routing is missing, all three values are taken from
    discovery. For multiple explicit domains, include the tenant default accepted
    domain: it is used for connector creation while rules cover the supplied domains.
.PARAMETER routing
    Optional routing mode: parallel (p) for Microsoft MX records or inline (i) for
    SEPPMAIL.cloud MX records. Explicit settings must agree with deployment discovery.
.PARAMETER region
    Provisioned cloud region: ch, de, prv or dev. If any required setup value is
    missing, the discovered region is used. Explicit settings must match discovery.
.PARAMETER force
    Remove the existing setup before creating connectors and rules again.
    This can disrupt mail flow; back up and review the existing configuration first.
.PARAMETER WhatIf
    Propagates the WhatIf preference to nested commands, but is NOT a complete dry run.
    New-SC365Connectors has unguarded tenant preparation changes. Discovery still
    runs and completion messages may appear even when guarded operations are skipped.
.PARAMETER Confirm
    Controls confirmations in nested commands. This wrapper has no separate
    ShouldProcess gate, and tenant preparation changes may occur without confirmation.
    -Confirm:$false does not suppress custom prompts.
.NOTES
    - none -
.LINK
    https://github.com/seppmail/seppmail365cloud
.EXAMPLE
    New-SC365Setup
     
    Automatically creates all Rules and Connectors in discovery mode.
    Parameters like Domain, Region and Routing are detected automatically.
.EXAMPLE
    New-SC365Setup -force
     
    Forces removal of existing setup and recreates Connectors and Rules.
    Useful for updates or when configuration errors need to be corrected.
.EXAMPLE
    New-SC365Setup -SEPPMAILCloudDomain contoso.com -routing parallel -region ch
     
    Creates a setup for domain contoso.com in parallel mode in Switzerland region.
    MX records remain pointing to Microsoft, mail is routed via Connector to SEPPMAIL.
.EXAMPLE
    New-SC365Setup -SEPPMAILCloudDomain contoso.de -routing inline -region de
     
    Creates a setup for domain contoso.de in inline mode in Germany/EU region.
    MX records must point to SEPPMAIL.cloud for inbound mail.
.EXAMPLE
    New-SC365Setup -SEPPMAILCloudDomain 'contoso.eu','contoso.com' -routing parallel -region de
     
    Creates rules for multiple domains, using the tenant default domain for connectors.
    Include the default accepted domain in the supplied list.
    This wrapper has no inboundOnly parameter; use New-SC365Connectors directly for inbound-only creation.
.EXAMPLE
    New-SC365Setup -SEPPMAILCloudDomain contoso.eu -routing parallel -region de -WhatIf
     
    Previews guarded operations, but can still change tenant preparation settings.
    Use only in a disposable test tenant; this is not a safe production dry run.
.EXAMPLE
    New-SC365Setup -SEPPMAILCloudDomain 'contoso.eu' -routing parallel -region de -Confirm
 
    Requests confirmations in nested commands. Unguarded preparation changes can still occur.
#>

function New-SC365Setup {
    [CmdLetBinding(
        SupportsShouldProcess=$true,
        ConfirmImpact = 'Medium'
        # HelpURI = 'https://github.com/seppmail/SEPPMAIL365cloud/blob/main/README.md'
    )]

    # Specifies a path to one or more locations.
    param(
        [Parameter(
            Mandatory=$false,
            HelpMessage="The primary domain, booked in the SEPPMAIL.cloud"
            )]
            [Alias('domain')]
            [ValidateNotNullOrEmpty()]
            [String[]]$SEPPMAILCloudDomain,
    
        [Parameter(
            Mandatory=$false,
            HelpMessage="Inline routing via SEPPMAIL (MX ==> SEPPMAIL), or routing via Microsoft (MX ==> Microsoft)"
            )]
            [ValidateNotNullOrEmpty()]
            [ValidateSet('parallel','inline','p','i')]
        [String]$routing,
    
        [Parameter(
            Mandatory=$false,
            HelpMessage="Physical location of your data"
            )]
            [ValidateSet('dev','prv','de','ch')]
        [String]$region,

        [Parameter(
            Mandatory=$false,
            HelpMessage="Removes existing setup"
        )]
        [switch]$force
    )

    Begin {
        if(!(Test-SC365ConnectionStatus)) {
            throw [System.Exception] "You're not connected to Exchange Online - please connect prior to using this CmdLet"
        } else {
            Write-Verbose "Connected to Exchange Organization `"$Script:ExODefaultDomain`"" -InformationAction Continue
        }

        # If user tries to use *.onmicrosoft.com domain ==> BREAK
        if ($SEPPMAILCloudDomain -like '*.onmicrosoft.com') {
            Write-Error "Domain $SEPPMAILCloudDomain is not intended for E-Mail sending and cannot be booked for the SEPPMAIL-cloud Service. Specify a custom domain of your tenant and retry."
            break
        }
        Write-Verbose "Detecting deployment status from SEPPMAIL.cloud setup"
        try {
            $deploymentInfo = Get-SC365DeploymentInfo
        } catch {
            Throw [System.Exception] "Could not autodetect SEPPMAIL.cloud deployment status, check SEPPMAIL.cloud portal deployment status"
        }

        Write-Verbose "Not enough parameters given, reading from Tenant, otherwise use data from console"
        if ((!($SEPPMAILCloudDomain)) -or (!($region)) -or (!($routing)) ) {
            # Customers where TDAD is set to *.onmicrosoft.com ==> BREAK
            if ($DeploymentInfo.SEPPMAILCloudDomain -like '*.onmicrosoft.com') {
                Write-Error "Domain $($DeploymentInfo.SEPPMAILCloudDomain) is set as the tenant default accepted domain. $($DeploymentInfo.SEPPMAILCloudDomain) is not intended for E-Mail sending and cannot be booked for the SEPPMAIL-cloud Service. Specify a custom domain of your tenant and retry or change the Default accepted domain in your Exchange Online tenant."
                break
            }
            if ($DeploymentInfo.DeployMentStatus -eq $false) {
                Write-Error "SEPPMAIL.cloud setup for domain $deploymentInfo.SEPPMAILCloudDomain is not (fully) deployed. Use Cloud-Portal and fix deployment."
                break
            } else {
                if ($Deploymentinfo) {
                            if ($deploymentInfo.Routing) {$Routing = $deploymentInfo.Routing} else {Write-Error "Cloud not autodetect routing info, use manual parameters"; break}
               if ($deploymentInfo.Routing -ne $routing) {Write-Error "SEPPMAIL.cloud is deployed with routing $deploymentInfo.Routing but the routing parameter is set to $routing, this will NOT WORK, exiting ..."; break}
                             if ($deploymentInfo.Region) {$Region = $deploymentInfo.Region} else {Write-Error "Could not autodetect region. Use manual parameters"; break}
                 if ($deploymentInfo.Region -ne $region) {Write-Error "SEPPMAIL.cloud is deployed in region $deploymentInfo.Region but the region parameter is set to $region, this will NOT WORK, exiting ..."; break}
                if ($DeploymentInfo.SEPPMAILCloudDomain) {$SEPPMAILCloudDomain = $DeploymentInfo.SEPPMAILCloudDomain} else {Write-Error "Could not autodetect SEPPMAILCloudDomain. Use manual parameters"; break}          
                }
            }
        } else {
            if ($deploymentInfo.routing -eq 'p') {$routing = 'parallel'}
            if ($deploymentInfo.routing -eq 'i') {$routing = 'inline'}

            Write-Verbose "Checking if console parameter fit to deployment Info"
            if ($SEPPMAILCloudDomain -ne $deploymentInfo.SEPPMAILCloudDomain) {Write-Warning "Domain `"$SEPPMAILCloudDomain`" does not fit to collected deployment info, just detected domain `"$($deploymentInfo.SEPPMAILcloudDomain)`""}
                                    if ($routing -ne $deploymentInfo.routing) {Write-Error "Routing mode `"$routing`" does not fit to deployment info, just detected routing mode `"$($DeploymentInfo.routing)`" STOPPING because deployment will FAIL";break}
                                      if ($region -ne $deploymentInfo.region) {Write-Error "Region `"$region`" does not fit to deployment info, just detected region `"$($deploymentInfo.region)`" STOPPING because deployment will FAIL";break}

            Write-Verbose "Confirming if $SEPPMAILCloudDomain is part or the tenant"
            $TenantDefaultDomain = $null
            foreach ($validationDomain in $SEPPMAILCloudDomain) {
                if ((Confirm-SC365TenantDefaultDomain -ValidationDomain $validationDomain) -eq $true) {
                    Write-verbose "Domain is part of the tenant and the Default Domain"
                    $TenantDefaultDomain = $ValidationDomain
                } else {
                    if ((Confirm-SC365TenantDefaultDomain -ValidationDomain $validationDomain) -eq $false) {
                        Write-verbose "Domain is part of the tenant"
                    } else {
                        Write-Error "Domain is NOT Part of the tenant"
                        break
                    }
                }
             }    
        }

    }
    Process {
        try {
            if ($force) {
                    Remove-SC365Setup
            }    
        } catch {
            throw [System.Exception] "Error: $($_.Exception.Message)"
            Write-Error "Setup removal failed. Try removing SEPPMAIL.cloud Rules and Connectors from the Microsoft portal admin.microsoft.com or with native Exchange Online PowerShell Module CmdLets."
            break
        }

        # For Connectors - use Tenant Default Domain
        # For TransportRules, use all domains in the array
        if ($SEPPMAILCloudDomain.count -le 1) {
            $ConnectorDomain = $SEPPMAILCloudDomain[0]
        } else {
            $ConnectorDomain = $TenantDefaultDomain
        }

        try {
            Write-Information '--- Creating in and outbound connectors ---' -InformationAction Continue
                New-SC365Connectors -SEPPMAILCloudDomain $ConnectorDomain -routing $routing -region $region
        } catch {
            throw [System.Exception] "Error: $($_.Exception.Message)"
            break
        }
        try {
            Write-Information '--- Creating transport rules ---' -InformationAction Continue
            New-SC365Rules -SEPPMAILCloudDomain $SEPPMAILCloudDomain -routing $routing
        } catch {
            throw [System.Exception] "Error: $($_.Exception.Message)"
            break
        }
    }
     End{
        Write-Information "--- Successfully created SEPPMAIL.cloud Setup for $SEPPMAILCloudDomain in region $region in $routing mode ---" -InformationAction Continue
        Write-Information "--- Wait a few minutes until changes are applied in the Microsoft cloud ---" -InformationAction Continue
        Write-Information "--- Afterwards, start testing E-Mails in and out ---" -InformationAction Continue
    }
}

<#
.SYNOPSIS
    Reads all Rules and Connectors for SEPPMAIL.cloud in an Exo-Tenant
.DESCRIPTION
    Based on autodiscovery, or forced values through parameters, Get-SC365Setup reads all connectors and rules from an Exo-Tenant
.NOTES
    - none -
.LINK
    https://github.com/seppmail/seppmail365cloud
.EXAMPLE
    Get-SC365Setup
     
    Automatically reads all SEPPMAIL.cloud Rules and Connectors in discovery mode.
    The routing mode and configuration are detected and displayed automatically.
     
    Returns a paginated output of all configured Connectors and Transport Rules.
.EXAMPLE
    Get-SC365Setup -Verbose
     
    Displays the paged configuration and diagnostic information about discovery.
.EXAMPLE
    Get-SC365Setup
    Get-SC365Rules | Export-Csv -Path "C:\Temp\SEPPMAIL-Rules.csv" -NoTypeInformation
     
    Reviews the setup on the host, then exports rule objects using Get-SC365Rules.
    Get-SC365Setup writes to Out-Host and does not emit configuration objects for export.
.EXAMPLE
    Get-SC365Setup
    Get-SC365Connectors -routing parallel | Where-Object {$_.Identity -like '*Outbound*'}
     
    Reviews the setup, then retrieves outbound connector objects for a parallel deployment.
    Use the connector cmdlet directly for filtering rather than capturing Get-SC365Setup.
.INPUTS
    None. This command has no function-specific parameters.
.OUTPUTS
    Paged host output only; no configuration objects are written to the success pipeline.
#>

function Get-SC365Setup {
    [CmdletBinding()]
    param()
    Begin {
        if(!(Test-SC365ConnectionStatus)) {
            throw [System.Exception] "You're not connected to Exchange Online - please connect prior to using this CmdLet"
        } else {
            Write-Verbose "Connected to Exchange Organization `"$Script:ExODefaultDomain`"" -InformationAction Continue
        }
        Write-Verbose "Detecting SEPPMAIL.cloud deployment scenario to read Exo Deployment"
        try {
            $deploymentInfo = Get-SC365DeploymentInfo
        } catch {
            Throw [System.Exception] "Could not autodetect SEPPMAIL.cloud Deployment Status, use manual parameters"
        }
        
        if ($deploymentInfo.DeployMentStatus -eq $false) {
            Write-Error "SEPPMAIL.cloud setup not (fully) deployed. Use Cloud-Portal and fix deployment."
            break
        } else {
            if ($deploymentInfo) {
                if ($deploymentInfo.Routing) {$Routing = $deploymentInfo.Routing} else {Write-Error "Cloud not autodetect routing info, use manual parameters"; break}
                if ($deploymentInfo.InBoundOnly -eq $true) {$InBoundOnly = $deploymentInfo.InBoundOnly} else {$InBoundOnly = $false}
            }
        }
    }
    Process {
        try {
            if ($InBoundOnly -eq $true) {
                Write-Verbose "Get SEPPMAIL.cloud Connectors in inbound-only mode"
                $smcConn = Get-SC365Connectors -Routing $routing -inboundOnly:$true
            } else {
                Write-Verbose "Get SEPPMAIL.cloud Connectors"
                $smcConn = Get-SC365Connectors -Routing $routing -inboundOnly:$false
            }
            if ($InBoundOnly -eq $false) {
                Write-Verbose "Get SEPPMAIL.cloud Transport Rules"
                $smcTRules = Get-SC365Rules
            }    
        }
        catch {
            Write-Warning "Found no or incomplete setup, please check manually in EAC."
            break
        }
    }
    End{
        Out-Host -InputObject $smcConn -Paging
        if ($InBoundOnly -eq $false) {
            Out-Host -InputObject $smcTRules -Paging
        }
     }
}

<#
.SYNOPSIS
    Updates the SEPPMAIL.cloud setup in Exchange Online by performing a controlled upgrade of transport rules and connectors.
 
.DESCRIPTION
    The `Update-SC365Setup` function helps update the SEPPMAIL.cloud integration with Exchange Online while minimizing disruptions.
    It follows a structured approach to renaming and replacing existing transport rules and connectors with updated versions.
 
    The update process includes:
    1. Checking for existing backup objects.
    2. Renaming existing SEPPMAIL.cloud transport rules to a backup name.
    3. Creating temporary connectors with a prefixed name.
    4. Reconfiguring outbound transport rules to use the new connectors.
    5. Renaming existing SEPPMAIL.cloud connectors to backup names.
    6. Reattaching old transport rules to the renamed backup connectors.
    7. Renaming the new connectors to their final names.
    8. Creating new transport rules in a disabled state for review.
 
    This function is designed for standard SEPPMAIL.cloud setups. If you have customizations in your Exchange Online environment,
    additional manual adjustments may be necessary.
 
.PARAMETER BackupName
    Specifies a custom prefix for the backup mail flow objects created during the update process.
    The default value is 'SC-BKP'.
 
.PARAMETER TempPrefix
    Specifies the prefix used for temporary connectors during the update process.
    The default value is 'temp'.
.PARAMETER WhatIf
    Preview only the operations protected by ShouldProcess or nested preferences.
    The update contains unguarded rule and connector changes; this is NOT a safe
    production dry run. The custom MURPHY acknowledgement prompt still appears.
.PARAMETER Confirm
    Request confirmation for guarded operations. Many update steps are not guarded.
    -Confirm:$false does not bypass the custom MURPHY acknowledgement prompt.
 
.EXAMPLE
    Update-SC365Setup
 
    Runs the update process using the default backup name ('SC-BKP') and temporary prefix ('temp').
 
.EXAMPLE
    Update-SC365Setup -BackupName "SEPPMAIL-Backup" -TempPrefix "TempConn"
 
    Runs the update process with custom naming for backup and temporary objects.
.EXAMPLE
    Update-SC365Setup -BackupName 'SC-BKP' -TempPrefix 'temp' -WhatIf
 
    Demonstrates partial preview behavior only. Unguarded update steps may still
    modify configuration after acknowledgement. Use only in a disposable test tenant.
.EXAMPLE
    Update-SC365Setup -BackupName 'SC-BKP' -TempPrefix 'temp' -Confirm
 
    Requests confirmation for guarded operations, in addition to the acknowledgement.
    Review the standard-setup restrictions and verify all objects after the update.
 
.NOTES
    - This script should only be used for standard SEPPMAIL.cloud setups.
    - After execution, manual verification and testing are recommended.
    - The old setup remains active until the administrator enables the new configuration.
 
.LINK
    https://github.com/seppmail/SEPPMAIL365cloud
#>

function Update-SC365Setup {
    [CmdletBinding(
        SupportsShouldProcess = $true
        )
    ]
    param(

        # Specifies the name for the backup to be created during the update process.
        [Parameter(
            Mandatory = $false,
            HelpMessage = "Provide a custom name for the backup mail flow object during the update process."
        )]
        [string]$BackupName = 'SC-BKP',

        # Specifies the name for the backup to be created during the update process.
        [Parameter(
            Mandatory = $false,
            HelpMessage = "Prefix for connectors for temporary swapping rules traffic"
        )]
        [string]$TempPrefix = 'temp'
    )

    begin {
        $existEAValue = $ErrorActionPreference
        $ErrorActionPreference = 'SilentlyContinue'
    }
    process {
        #region info block
        $bannerLines = @(
            'This script is a helper and provides basic steps to upgrade your'
            'SEPPMAIL.cloud/Exchange integration. It covers only STANDARD Setups!'
            ''
            'The Script will:'
            ' 1.) Check if there are any orphaned rule or connector objects'
            ' 2.) Rename SEPPMAIL.cloud Transport rules to $backupName'
            ' 3.) Create Connectors with Temp Name'
            ' 4.) Set (200) outbound transport rule to New-Connector'
            ' 5.) Rename SEPPMAIL.cloud Connectors to $backupName'
            ' 6.) Attach old Transport rules to old Connector with BackupNam'
            ' 7.) Rename NEW Connectors to original names'
            ' 8.) Create new transport rules -PlacementPriority BOTTOM'
            ' ----------------- OLD SETUP STILL RUNNING ------------------'
            ''
            ''
            'Check any:'
            ' - customizations to SEPPMAIL.cloud rules'
            ' - other corporate transport rules'
            ' - disclaimer Services integrated via rules'
            ' - or other special scenarios in your Exo-Tenant'
            ''
            'you need to adapt/change/post-configure the outcome of this script,'
            'and ENABLE the new setup in Exchange Online.'
            ''
            'DO NOT JUST FIRE IT UP AND HOPE THINGS ARE GOING TO WORK !!!!!!'
        )
        $contentWidth = ($bannerLines | Measure-Object -Property Length -Maximum).Maximum
        $border = '─' * ($contentWidth + 2)

        Write-SEPPMAILText -Colorset Action -Text ("┌{0}┐" -f $border)
        foreach ($line in $bannerLines) {
            Write-SEPPMAILText -Colorset Action -Text ("│ {0} │" -f $line.PadRight($contentWidth))
        }
        Write-SEPPMAILText -Colorset Action -Text ("└{0}┘" -f $border)
        #endregion
        $response = Read-Host "I have read and understood the above warning (Type MURPHY if you agree)!"
        if ($response -eq 'MURPHY') {

            Write-Verbose '1 - Checking if there are existing Backup objects in the Exchange Tenant'

            # Define total steps for progress calculation
            $totalSteps = 8
            $step = 0
            
            $backupWildCard = '[' + $backupName + '*'
            Write-Verbose "1a - Checking if there are any orphaned backup objects"
            if (!((Get-InboundConnector -Identity $BackupWildcard -ea SilentlyContinue) -or 
                  (Get-OutboundConnector -Identity $backupWildCard -ea SilentlyContinue) -or 
                  (Get-TransportRule -Identity $backupWildCard -ea SilentlyContinue))) {
            
                # Step 1: Get Deployment Info
                $step++
                Write-Progress -Activity "Updating SEPPMAIL.cloud Setup" -Status "Retrieving Deployment Info ($step/$totalSteps)" -PercentComplete (($step / $totalSteps) * 100)
                Write-Verbose "1b - Getting DeploymentInfo"
                $DeplInfo = Get-SC365DeploymentInfo
            
                # Step 2: Rename Existing Rules
                $step++
                Write-Progress -Activity "Updating SEPPMAIL.cloud Setup" -Status "Renaming Transport Rules ($step/$totalSteps)" -PercentComplete (($step / $totalSteps) * 100)
                Write-Verbose "2 - Rename existing SEPPMAIL.cloud rules"

                # Get all transport rules that match SEPPMAIL.cloud pattern
                $oldTrpRls = Get-TransportRule -Identity '[SEPPMAIL.cloud]*'
                $totalRules = $oldTrpRls.Count
                $ruleCounter = 0  # Initialize sub-progress counter

                foreach ($rule in $oldTrpRls) {
                    $ruleCounter++
                
                    # Sub-Progress Bar: Shows progress for each rule being renamed
                    Write-Progress -Activity "Renaming Transport Rules" `
                                   -Status "Renaming ($ruleCounter of $totalRules): $($rule.Name)" `
                                   -PercentComplete (($ruleCounter / $totalRules) * 100) `
                                   -Id 2  # Unique ID for the sub-progress bar
                
                    # Rename the rule
                    Set-TransportRule -Identity $rule.Name -Name ($rule.Name -replace 'SEPPMAIL.Cloud', $BackupName)
                }

                # Clear the sub-progress bar once renaming is done
                Write-Progress -Id 2 -Activity "Renaming Transport Rules" -Completed            

                # Step 3: Create New Connectors
                $step++
                Write-Progress -Activity "Updating SEPPMAIL.cloud Setup" -Status "Creating New Connectors ($step/$totalSteps)" -PercentComplete (($step / $totalSteps) * 100)
                Write-Verbose "3 - Creating new connectors with temp name" 
                if ($PSCmdlet.ShouldProcess('New connectors', 'create')) {
                    $newConnectors = New-SC365connectors -SEPPMAILCloudDomain $DeplInfo.SEPPMAILCloudDomain -region $DeplInfo.region -routing $DeplInfo.routing -NamePrefix $tempPrefix 
                }
            
                # Step 4: Update Transport Rules to Use New Connectors
                $step++
                Write-Progress -Activity "Updating SEPPMAIL.cloud Setup" -Status "Updating Transport Rules ($step/$totalSteps)" -PercentComplete (($step / $totalSteps) * 100)
                Write-Verbose "4 - Set outbound rules to new connector"

                # Get the current outbound connector
                $oldObc = Get-OutboundConnector -Identity '[SEPPMAIL.cloud] Outbound-*'
                [string]$tempObcName = $TempPrefix + $($OldObc.Identity)

                # Get transport rules that need updating
                $rulesToChange = Get-TransportRule -Identity '[*' | Where-Object {($_.RouteMessageOutboundConnector) -and ($_.Name -like "*$backupName*")}
                $totalRules = $rulesToChange.Count
                $ruleCounter = 0  # Initialize sub-progress counter

                foreach ($rule in $rulesToChange) {
                    $ruleCounter++                
                    # Sub-Progress Bar: Show progress for each rule being updated
                    Write-Progress -Activity "Updating Transport Rules" `
                                   -Status "Updating ($ruleCounter of $totalRules): $($rule.Name)" `
                                   -PercentComplete (($ruleCounter / $totalRules) * 100) `
                                   -Id 3  # Unique ID for the sub-progress bar
                
                    # Update the transport rule to use the new connector
                    Set-TransportRule -Identity $($rule.Identity) -RouteMessageOutboundConnector $tempObcName 
                }

                # Clear the sub-progress bar once the update is complete
                Write-Progress -Id 3 -Activity "Updating Transport Rules" -Completed

                # Step 5: Rename Old Connectors
                $step++
                Write-Progress -Activity "Updating SEPPMAIL.cloud Setup" -Status "Renaming Old Connectors ($step/$totalSteps)" -PercentComplete (($step / $totalSteps) * 100)
                Write-Verbose "5 - Rename existing SEPPMAIL.cloud Connectors to $backupName"
                $oldIbc = Get-InboundConnector -Identity '[SEPPMAIL.cloud] Inbound-*' 
                Set-InboundConnector -Identity $($OldIbc.Identity) -Name ($($OldIbc.Identity) -replace 'SEPPMAIL.Cloud', $backupName) 
                $oldObc = Get-OutBoundConnector -Identity "[SEPPMAIL.cloud] OutBound-*"
                Set-OutBoundConnector -Identity $($oldObc.Identity) -Name ($oldObc.Identity -replace 'SEPPMAIL.Cloud', $backupName) 
            
                # Step 6: Attach Old Transport Rules to Renamed Backup Connectors
                $step++
                Write-Progress -Activity "Updating SEPPMAIL.cloud Setup" -Status "Reattaching Old Rules ($step/$totalSteps)" -PercentComplete (($step / $totalSteps) * 100)
                Write-Verbose "6 - Set outbound rule to old backup connector again"
                $bkpConnWildcard = "[" + $backupName + "]*"
                $bkpObc = Get-OutboundConnector -Identity $bkpConnWildcard
                foreach ($rule in $rulesToChange) {
                    Set-TransportRule -Identity $($rule.Identity) -RouteMessageOutboundConnector $bkpObc 
                }
            
                # Step 7: Rename New Connectors to Their Final Names
                $step++
                Write-Progress -Activity "Updating SEPPMAIL.cloud Setup" -Status "Renaming New Connectors ($step/$totalSteps)" -PercentComplete (($step / $totalSteps) * 100)
                Write-Verbose "7 - Rename existing $tempPrefix connectors to final name"
                $finalObCName = ($newConnectors | Where-Object Identity -like '*OutBound*').Identity -replace "^$([regex]::Escape($tempPrefix))", ""
                Set-OutboundConnector -Identity ($newConnectors | Where-Object Identity -like '*OutBound*').Identity -Name $finalObcName 
                $finalIbcName = ($newConnectors | Where-Object Identity -like '*Inbound*').Identity -replace "^$([regex]::Escape($tempPrefix))", ""
                Set-InBoundConnector -Identity ($newConnectors | Where-Object Identity -like '*InBound*').Identity -Name $finalIbcName 
            
                # Step 8: Create New Transport Rules in Disabled State for Review
                $step++
                Write-Progress -Activity "Updating SEPPMAIL.cloud Setup" -Status "Creating New Transport Rules ($step/$totalSteps)" -PercentComplete (($step / $totalSteps) * 100)
                Write-Verbose "8 - Creating new Transport Rules" 
                New-SC365Rules -SEPPMAILCloudDomain $DeplInfo.SEPPMAILCloudDomain -routing $DeplInfo.routing -PlacementPriority Top -Disabled 
            
                # Complete Progress Bar
                Write-Progress -Activity "Updating SEPPMAIL.cloud Setup" -Status "Completed" -Completed
                
$switchFinalConfig = @"
# To enable the new configuration, use something like the command below.
Get-TransportRule | Where-Object {`$_.Name -like '*[SEPPMAIL.cloud]*'} | Enable-TransportRule
 
# To remove the old configuration, use something like the code below as an example.
Get-TransportRule | Where-Object {`$_.Name -like '*$BackupName*'} | Remove-TransportRule -Confirm:`$false
Get-InboundConnector |? {`$_.Identity -like '*$BackupName*'}|Remove-InboundConnector -Confirm:`$false
Get-OutboundConnector |? {`$_.Identity -like '*$BackupName*'}|Remove-OutboundConnector -Confirm:`$false
"@

              
                # Inform User About Next Steps
                $bannerLines = @(
                    "The CmdLet has finished and the OLD SETUP $backupName IS STILL ACTIVE"
                    ''
                    'CUSTOMIZE your setup and ENABLE the new setup when done.'
                    ''
                    "After final tests you can DELETE the $backupName objects"
                    'Find some example commands below:'
                )
                $contentWidth = ($bannerLines | Measure-Object -Property Length -Maximum).Maximum
                $border = '─' * ($contentWidth + 2)

                Write-SEPPMAILText -Colorset Action -Text ("┌{0}┐" -f $border)
                foreach ($line in $bannerLines) {
                    Write-SEPPMAILText -Colorset Action -Text ("│ {0} │" -f $line.PadRight($contentWidth))
                }
                Write-SEPPMAILText -Colorset Action -Text ("└{0}┘" -f $border)

                $switchFinalConfig.Replace('*BKP*',"*$backupName*")
                
                #>
            }
            else {
                Write-Error "STOPPING - Found Existing Backup Objects - clean up the environment from $BackupName objects (rules and connectors) and TRY again"
                break
            }
        } else {
            Write-Host "Wise decision! Analyze your integration with New-SC365ExoReport and come back again if you are more familiar with the environment." -ForegroundColor Green -BackgroundColor DarkGray
            }
        }
        end {
            $ErrorActionPreference = $existEAValue
        }
    }

function New-CP365Setup {
    [CmdLetBinding(
        SupportsShouldProcess = $true,
        ConfirmImpact = 'Medium'
        #HelpURI = ''
    )]

    # Specifies a path to one or more locations.
    param(
        [Parameter(
            Mandatory=$false,
            HelpMessage="Removes existing setup"
        )]
        [switch]$force
    )

    Begin {
        if(!(Test-SC365ConnectionStatus)) {
            throw [System.Exception] "You're not connected to Exchange Online - please connect prior to using this CmdLet"
        } else {
            Write-Verbose "Connected to Exchange Organization `"$Script:ExODefaultDomain`"" -InformationAction Continue
        }

        # If user tries to use *.onmicrosoft.com domain ==> BREAK
        $Tdd = (Get-AcceptedDomain |where "Default" -eq $true).DomainName
        if ($Tdd -like '*.onmicrosoft.com') {
            Write-Error "Domain $tdd is not intended for E-Mail sending and cannot be booked for the Cyberpilot Service. Specify a custom domain of your tenant and retry."
            break
        }
        $CPparams = Get-CP365Config
        #TODO: Enable when CmdLet ready
        <#Write-Verbose "Detecting deployment status from SEPPMAIL.cloud setup"
        try {
            $deploymentInfo = Get-CP365DeploymentInfo
        } catch {
            Throw [System.Exception] "Could not autodetect SEPPMAIL.cloud deployment status, check SEPPMAIL.cloud portal deployment status"
        }
        #>

    }
    
    Process {
        try {
            if ($force) {
                    Remove-CP365Setup
            }    
        } catch {
            throw [System.Exception] "Error: $($_.Exception.Message)"
            Write-Error "Setup removal failed. Try removing Cyberpilot Settings from the Microsoft portal admin.microsoft.com or with native Exchange Online PowerShell Module CmdLets."
            break
        }

        try {
            Write-Information '--- Creating Cyberpilot inbound connector ---' -InformationAction Continue
                New-CP365Connector
        } catch {
            throw [System.Exception] "Error: $($_.Exception.Message)"
            break
        }
        try {
            Write-Information '--- Creating Cyperpilot phishing simulation override rules ---' -InformationAction Continue
            if (!(Get-ExoPhishSimOverrideRule).Name) {
                New-ExoPhishSimOverrideRule -AddDomains $CPparams.CyberPilot.domains.AllowedDomains -AddSenderIpRanges $CPparams.CyberPilot.IPs.IPv4AllowList -Identity $PhishSimOverrideRuleId
            } else {
                Set-ExoPhishSimOverrideRule -AddDomains $CPparams.CyberPilot.domains.AllowedDomains -AddSenderIpRanges $CPparams.CyberPilot.IPs.IPv4AllowList -Identity $PhishSimOverrideRuleId
            }
        } catch {
            throw [System.Exception] "Error: $($_.Exception.Message)"
            break
        }

        try {
            Write-Information '--- Creating Cyperpilot tenant allowblockList items ---' -InformationAction Continue
            New-TenantAllowBlockListItems -Allow -ListType Url -ListSubType AdvancedDelivery -Entries $CPparams.CyberPilot.SimURLs.SimURLs
        } catch {
            throw [System.Exception] "Error: $($_.Exception.Message)"
            break
        }
    }
     End{
        Write-Information "--- Successfully created Cyberpilot setup for $TDD. ---" -InformationAction Continue
        Write-Information "--- Wait a few minutes until changes are applied in the Microsoft cloud ---" -InformationAction Continue
    }
}


Register-ArgumentCompleter -CommandName New-SC365Setup -ParameterName SEPPMAILCloudDomain -ScriptBlock $paramDomSB


# SIG # Begin signature block
# MIIQVQYJKoZIhvcNAQcCoIIQRjCCEEICAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCClLjdvzjCV4O1D
# mio4chSHywIIFDBU5d38mVqkad5jKaCCDJEwggYaMIIEAqADAgECAhBiHW0MUgGe
# O5B5FSCJIRwKMA0GCSqGSIb3DQEBDAUAMFYxCzAJBgNVBAYTAkdCMRgwFgYDVQQK
# Ew9TZWN0aWdvIExpbWl0ZWQxLTArBgNVBAMTJFNlY3RpZ28gUHVibGljIENvZGUg
# U2lnbmluZyBSb290IFI0NjAeFw0yMTAzMjIwMDAwMDBaFw0zNjAzMjEyMzU5NTla
# MFQxCzAJBgNVBAYTAkdCMRgwFgYD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