Roles.psm1

$script:ModuleRoot = $PSScriptRoot
$script:ModuleVersion = (Import-PSFPowerShellDataFile -Path "$($script:ModuleRoot)\Roles.psd1").ModuleVersion

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = Get-PSFConfigValue -FullName Roles.Import.DoDotSource -Fallback $false
if ($Roles_dotsourcemodule) { $script:doDotSource = $true }

<#
Note on Resolve-Path:
All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator.
This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS.
Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist.
This is important when testing for paths.
#>


# Detect whether at some level loading individual module files, rather than the compiled module was enforced
$importIndividualFiles = Get-PSFConfigValue -FullName Roles.Import.IndividualFiles -Fallback $false
if ($Roles_importIndividualFiles) { $importIndividualFiles = $true }
if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true }
if ("<was compiled>" -eq '<was not compiled>') { $importIndividualFiles = $true }
    
function Import-ModuleFile
{
    <#
        .SYNOPSIS
            Loads files into the module on module import.
         
        .DESCRIPTION
            This helper function is used during module initialization.
            It should always be dotsourced itself, in order to proper function.
             
            This provides a central location to react to files being imported, if later desired
         
        .PARAMETER Path
            The path to the file to load
         
        .EXAMPLE
            PS C:\> . Import-ModuleFile -File $function.FullName
     
            Imports the file stored in $function according to import policy
    #>

    [CmdletBinding()]
    Param (
        [string]
        $Path
    )
    
    $resolvedPath = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($Path).ProviderPath
    if ($doDotSource) { . $resolvedPath }
    else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText($resolvedPath))), $null, $null) }
}

#region Load individual files
if ($importIndividualFiles)
{
    # Execute Preimport actions
    foreach ($path in (& "$ModuleRoot\internal\scripts\preimport.ps1")) {
        . Import-ModuleFile -Path $path
    }
    
    # Import all internal functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Import all public functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Execute Postimport actions
    foreach ($path in (& "$ModuleRoot\internal\scripts\postimport.ps1")) {
        . Import-ModuleFile -Path $path
    }
    
    # End it here, do not load compiled code below
    return
}
#endregion Load individual files

#region Load compiled code
<#
This file loads the strings documents from the respective language folders.
This allows localizing messages and errors.
Load psd1 language files for each language you wish to support.
Partial translations are acceptable - when missing a current language message,
it will fallback to English or another available language.
#>

Import-PSFLocalizedString -Path "$($script:ModuleRoot)\en-us\*.psd1" -Module 'Roles' -Language 'en-US'

function Assert-Elevation
{
<#
    .SYNOPSIS
        Asserts that the current PowerShell process runs with elevation.
     
    .DESCRIPTION
        Asserts that the current PowerShell process runs with elevation.
        Will always succeed on non-windows computers.
     
    .PARAMETER Cmdlet
        The $PSCmdlet variable of the calling command, used to throw the exception in the context of the caller.
     
    .EXAMPLE
        PS C:\> Assert-Elevation -Cmdlet $PSCmdlet
     
        Asserts that the current PowerShell process runs with elevation.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        $Cmdlet
    )
    
    process
    {
        if (Test-PSFPowerShell -Elevated) { return }
        if (Get-PSFConfigValue -FullName 'Roles.Validation.SkipElevationTest') { return }
        
        $exception = [System.Security.SecurityException]::new("Insufficient access, elevation required! This operation requires running PowerShell 'As Administrator'")
        $record = [System.Management.Automation.ErrorRecord]::new($exception, "NotElevated", [System.Management.Automation.ErrorCategory]::SecurityError, $null)
        $Cmdlet.ThrowTerminatingError($record)
    }
}

function Assert-RoleRole
{
<#
    .SYNOPSIS
        Asserts that the specified role is part of the specified system.
     
    .DESCRIPTION
        Asserts that the specified role is part of the specified system.
     
    .PARAMETER System
        The system to ensure exists.
        May be an empty string (in which case it is guaranteed to fail).
     
    .PARAMETER Role
        The role that should be part of the current system.
        May be an empty string (in which case it is guaranteed to fail).
     
    .PARAMETER Cmdlet
        The $PSCmdlet variable of the calling command.
     
    .EXAMPLE
        PS C:\> Assert-RoleRole -System $System -Role $Name -Cmdlet $PSCmdlet
     
        Asserts that the specified role is part of the specified system.
#>

    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $true)]
        [AllowEmptyString()]
        [string]
        $System,
        
        [Parameter(Mandatory = $true)]
        [AllowEmptyString()]
        [string]
        $Role,
        
        [Parameter(Mandatory = $true)]
        $Cmdlet
    )
    
    process
    {
        if ($System -and $Role) {
            $systemPath = Get-RolePath -System $System -Role $Role
            if (Test-Path -Path $systemPath) { return }
        }
        
        $exception = [System.ArgumentException]::new("Bad Role / System combination. Make sure the selected role '$Role' exists in '$System'", "Role")
        $record = [System.Management.Automation.ErrorRecord]::new($exception, "UnknownRole", [System.Management.Automation.ErrorCategory]::InvalidArgument, $null)
        $Cmdlet.ThrowTerminatingError($record)
    }
}

function Assert-RoleSystem
{
<#
    .SYNOPSIS
        Assert that the selected Role System is valid.
     
    .DESCRIPTION
        Assert that the selected Role System is valid.
     
    .PARAMETER System
        The system to ensure exists.
        May be an empty string (in which case it is guaranteed to fail).
     
    .PARAMETER Cmdlet
        The $PSCmdlet variable of the calling command.
     
    .EXAMPLE
        PS C:\> Assert-System -System $System -Cmdlet $PSCmdlet
     
        Asserts that the Role System provided in $System exists
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [AllowEmptyString()]
        [string]
        $System,
        
        [Parameter(Mandatory = $true)]
        $Cmdlet
    )
    
    process{
        if ($System) {
            $systemBase64 = $System.ToLower() | ConvertTo-Base64
            $systemPath = Join-Path -Path $script:roleSystemPath -ChildPath $systemBase64
            if (Test-Path -Path $systemPath) { return }
        }
        
        $exception = [System.ArgumentException]::new("Bad Role System. Be sure to specify a valid system or execute Select-RoleSystem to select a system to use!", "System")
        $record = [System.Management.Automation.ErrorRecord]::new($exception, "UnknownSystem", [System.Management.Automation.ErrorCategory]::InvalidArgument, $null)
        $Cmdlet.ThrowTerminatingError($record)
    }
}

function ConvertFrom-Base64 {
<#
    .SYNOPSIS
        Convert a string from Base64.
     
    .DESCRIPTION
        Convert a string from Base64.
     
    .PARAMETER Text
        The base64 text to convert
     
    .EXAMPLE
        PS C:\> $role | ConvertTo-Base64
     
        Convert the string stored in $role to base 64.
#>

    [OutputType([string])]
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [AllowEmptyString()]
        [string[]]
        $Text
    )
    
    process {
        foreach ($textItem in $Text) {
            try {
                $bytes = [System.Convert]::FromBase64String($textItem)
                [System.Text.Encoding]::UTF8.GetString($bytes)
            }
            catch { Write-Error $_ }
        }
    }
}

function ConvertTo-Base64
{
<#
    .SYNOPSIS
        Convert a string to Base64.
     
    .DESCRIPTION
        Convert a string to Base64.
     
    .PARAMETER Text
        The text to convert
     
    .EXAMPLE
        PS C:\> $role | ConvertTo-Base64
     
        Convert the string stored in $role to base 64.
#>

    [OutputType([string])]
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [AllowEmptyString()]
        [string[]]
        $Text
    )
    
    process
    {
        foreach ($textItem in $Text) {
            try {
                $bytes = [System.Text.Encoding]::UTF8.GetBytes($textItem)
                [Convert]::ToBase64String($bytes)
            }
            catch { Write-Error $_ }
        }
    }
}

function Get-LdapObject {
    <#
        .SYNOPSIS
            Use LDAP to search in Active Directory
 
        .DESCRIPTION
            Utilizes LDAP to perform swift and efficient LDAP Queries.
 
        .PARAMETER LdapFilter
            The search filter to use when searching for objects.
            Must be a valid LDAP filter.
 
        .PARAMETER Property
            The properties to retrieve.
            Keep bandwidth in mind and only request what is needed.
 
        .PARAMETER SearchRoot
            The root path to search in.
            This generally expects either the distinguished name of the Organizational unit or the DNS name of the domain.
            Alternatively, any legal LDAP protocol address can be specified.
 
        .PARAMETER Configuration
            Rather than searching in a specified path, switch to the configuration naming context.
 
        .PARAMETER Raw
            Return the raw AD object without processing it for PowerShell convenience.
 
        .PARAMETER PageSize
            Rather than searching in a specified path, switch to the schema naming context.
 
        .PARAMETER MaxSize
            The maximum number of items to return.
 
        .PARAMETER SearchScope
            Whether to search all OUs beneath the target root, only directly beneath it or only the root itself.
     
        .PARAMETER AddProperty
            Add additional properties to the output object.
            Use to optimize performance, avoiding needing to use Add-Member.
 
        .PARAMETER Server
            The server to contact for this query.
 
        .PARAMETER Credential
            The credentials to use for authenticating this query.
     
        .PARAMETER TypeName
            The name to give the output object
 
        .EXAMPLE
            PS C:\> Get-LdapObject -LdapFilter '(PrimaryGroupID=516)'
             
            Searches for all objects with primary group ID 516 (hint: Domain Controllers).
    #>

    [Alias('ldap')]
    [CmdletBinding(DefaultParameterSetName = 'SearchRoot')]
    param (
        [Parameter(Mandatory = $true, Position = 0)]
        [string]
        $LdapFilter,
        
        [Alias('Properties')]
        [string[]]
        $Property = "*",
        
        [Parameter(ParameterSetName = 'SearchRoot')]
        [Alias('SearchBase')]
        [string]
        $SearchRoot,
        
        [Parameter(ParameterSetName = 'Configuration')]
        [switch]
        $Configuration,
        
        [switch]
        $Raw,
        
        [ValidateRange(1, 1000)]
        [int]
        $PageSize = 1000,
        
        [Alias('SizeLimit')]
        [int]
        $MaxSize,
        
        [System.DirectoryServices.SearchScope]
        $SearchScope = 'Subtree',
        
        [System.Collections.Hashtable]
        $AddProperty,
        
        [string]
        $Server,
        
        [PSCredential]
        $Credential,
        
        [Parameter(DontShow = $true)]
        [string]
        $TypeName
    )
    
    begin {
        #region Utility Functions
        function Get-PropertyName {
            [OutputType([string])]
            [CmdletBinding()]
            param (
                [string]
                $Key,
                
                [string[]]
                $Property
            )
            
            if ($hit = @($Property).Where{ $_ -eq $Key }) { return $hit[0] }
            if ($Key -eq 'ObjectClass') { return 'ObjectClass' }
            if ($Key -eq 'ObjectGuid') { return 'ObjectGuid' }
            if ($Key -eq 'ObjectSID') { return 'ObjectSID' }
            if ($Key -eq 'DistinguishedName') { return 'DistinguishedName' }
            if ($Key -eq 'SamAccountName') { return 'SamAccountName' }
            $script:culture.TextInfo.ToTitleCase($Key)
        }
        #endregion Utility Functions
        
        #region Prepare Searcher
        $searcher = New-Object system.directoryservices.directorysearcher
        $searcher.PageSize = $PageSize
        $searcher.SearchScope = $SearchScope
        
        if ($MaxSize -gt 0) {
            $Searcher.SizeLimit = $MaxSize
        }
        
        if ($SearchRoot) {
            $searcher.SearchRoot = New-DirectoryEntry -Path $SearchRoot -Server $Server -Credential $Credential
        }
        else {
            $searcher.SearchRoot = New-DirectoryEntry -Server $Server -Credential $Credential
        }
        if ($Configuration) {
            $searcher.SearchRoot = New-DirectoryEntry -Path ("LDAP://CN=Configuration,{0}" -f $searcher.SearchRoot.distinguishedName[0]) -Server $Server -Credential $Credential
        }
        
        Write-PSFMessage -String Get-LdapObject.SearchRoot -StringValues $SearchScope, $searcher.SearchRoot.Path -Level Debug
        
        if (Test-PSFParameterBinding -ParameterName Credential) {
            $searcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry($searcher.SearchRoot.Path, $Credential.UserName, $Credential.GetNetworkCredential().Password)
        }
        
        $searcher.Filter = $LdapFilter
        
        foreach ($propertyName in $Property) {
            $null = $searcher.PropertiesToLoad.Add($propertyName)
        }
        
        Write-PSFMessage -String Get-LdapObject.Searchfilter -StringValues $LdapFilter -Level Debug
        #endregion Prepare Searcher
    }
    process {
        try {
            foreach ($ldapobject in $searcher.FindAll()) {
                if ($Raw) {
                    $ldapobject
                    continue
                }
                #region Process/Refine Output Object
                $resultHash = @{ }
                foreach ($key in $ldapobject.Properties.Keys) {
                    $resultHash[(Get-PropertyName -Key $key -Property $Property)] = switch ($key) {
                        'ObjectClass' { $ldapobject.Properties[$key][-1] }
                        'ObjectGuid' { [guid]::new(([byte[]]($ldapobject.Properties[$key] | Write-Output))) }
                        'ObjectSID' { [System.Security.Principal.SecurityIdentifier]::new(([byte[]]($ldapobject.Properties[$key] | Write-Output)), 0) }
                        
                        default { $ldapobject.Properties[$key] | Write-Output }
                    }
                }
                if ($resultHash.ContainsKey("ObjectClass")) { $resultHash["PSTypeName"] = $resultHash["ObjectClass"] }
                if ($TypeName) { $resultHash["PSTypeName"] = $TypeName }
                if ($AddProperty) { $resultHash += $AddProperty }
                $item = [pscustomobject]$resultHash
                Add-Member -InputObject $item -MemberType ScriptMethod -Name ToString -Value {
                    if ($this.DistinguishedName) { $this.DistinguishedName }
                    else { $this.AdsPath }
                } -Force -PassThru
                #endregion Process/Refine Output Object
            }
        }
        catch {
            Stop-PSFFunction -String 'Get-LdapObject.SearchError' -ErrorRecord $_ -Cmdlet $PSCmdlet -EnableException $true
        }
    }
}

function Get-RolePath {
<#
    .SYNOPSIS
        Resolve the path of the specified role.
     
    .DESCRIPTION
        Resolve the path of the specified role.
     
    .PARAMETER Role
        Name of the role to resolve.
     
    .PARAMETER System
        System in which the role is included.
     
    .EXAMPLE
        PS C:\> Get-RolePath -Role $Role -System $System
     
        Returns the path to the role $Role
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $Role,
        
        [Parameter(Mandatory = $true)]
        [string]
        $System
    )
    
    process {
        Join-Path -Path (Get-RoleSystemPath -System $System) -ChildPath ($Role.ToLower() | ConvertTo-Base64)
    }
}

function Get-RoleSystemPath {
<#
    .SYNOPSIS
        Return the path to the folder of the given Role System.
     
    .DESCRIPTION
        Return the path to the folder of the given Role System.
     
    .PARAMETER System
        The System for which to provide the path.
     
    .EXAMPLE
        PS C:\> Get-RoleSystemPath -System 'VMDeploy'
     
        Get the path to the Role System "VMDeploy"'s folder.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $System
    )
    process {
        Join-Path -Path $script:roleSystemPath -ChildPath ($System.ToLower() | ConvertTo-Base64)
    }
}

function New-DirectoryEntry {
    <#
        .SYNOPSIS
            Generates a new directoryy entry object.
         
        .DESCRIPTION
            Generates a new directoryy entry object.
         
        .PARAMETER Path
            The LDAP path to bind to.
         
        .PARAMETER Server
            The server to connect to.
         
        .PARAMETER Credential
            The credentials to use for the connection.
         
        .EXAMPLE
            PS C:\> New-DirectoryEntry
 
            Creates a directory entry in the default context.
 
        .EXAMPLE
            PS C:\> New-DirectoryEntry -Server dc1.contoso.com -Credential $cred
 
            Creates a directory entry in the default context of the target server.
            The connection is established to just that server using the specified credentials.
    #>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding()]
    param (
        [string]
        $Path,
        
        [AllowEmptyString()]
        [string]
        $Server,
        
        [PSCredential]
        [AllowNull()]
        $Credential
    )
    
    if (-not $Path) { $resolvedPath = '' }
    elseif ($Path -like "LDAP://*") { $resolvedPath = $Path }
    elseif ($Path -notlike "*=*") { $resolvedPath = "LDAP://DC={0}" -f ($Path -split "\." -join ",DC=") }
    else { $resolvedPath = "LDAP://$($Path)" }
    
    if ($Server -and ($resolvedPath -notlike "LDAP://$($Server)/*")) {
        $resolvedPath = ("LDAP://{0}/{1}" -f $Server, $resolvedPath.Replace("LDAP://", "")).Trim("/")
    }
    
    if (($null -eq $Credential) -or ($Credential -eq [PSCredential]::Empty)) {
        if ($resolvedPath) { New-Object System.DirectoryServices.DirectoryEntry($resolvedPath) }
        else {
            $entry = New-Object System.DirectoryServices.DirectoryEntry
            New-Object System.DirectoryServices.DirectoryEntry(('LDAP://{0}' -f $entry.distinguishedName[0]))
        }
    }
    else {
        if ($resolvedPath) { New-Object System.DirectoryServices.DirectoryEntry($resolvedPath, $Credential.UserName, $Credential.GetNetworkCredential().Password) }
        else { New-Object System.DirectoryServices.DirectoryEntry(("LDAP://DC={0}" -f ($env:USERDNSDOMAIN -split "\." -join ",DC=")), $Credential.UserName, $Credential.GetNetworkCredential().Password) }
    }
}

function Resolve-ADEntity {
<#
    .SYNOPSIS
        Resolve an active directory identity into SID.
     
    .DESCRIPTION
        Resolve an active directory identity into SID.
     
    .PARAMETER Name
        The name of the entity to resolve.
        Can be a distinguished name, SID, SamAccountName, NT Account or User Principal Name.
        AD entity can be anything that holds a SID / SamAccountName.
         
        Will try to resolve identities acress all domains in the forest if ambiguous.
        It will prefer the current domain over others.
     
    .EXAMPLE
        PS C:\> Resolve-ADEntity -Name max
     
        Resolves the user max as a SamAccountName
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $Name
    )
    
    begin {
        #region Utility Functions
        function ConvertFrom-Name {
            [CmdletBinding()]
            param (
                [string]
                $Name
            )
            
            $result = [PSCustomObject]@{
                Username = ""
                Type     = "unknown"
                Domain   = ""
                SID         = ""
                Input    = $Name
            }
            
            # Case: User Principal Name
            if ($Name -match '^[\d\w-_\.]+@[\d\w-_\.]+') {
                $result.Username = $Name
                $result.Type = 'UPN'
                $result.Domain = ($Name -split "@")[-1]
                return $result
            }
            
            # Case: Distinguished Name
            if ($Name -like "*,DC=*") {
                $result.Username = $Name
                $result.Type = 'DN'
                $result.Domain = ($Name -split ",DC=" | Select-Object -Skip 1) -join "."
                return $result
            }
            
            # Case: SID
            if ($Name -as [System.Security.Principal.SecurityIdentifier]) {
                $result.Username = $Name
                $result.SID = $Name
                $result.Type = 'SID'
                $result.Domain = ($Name -as [System.Security.Principal.SecurityIdentifier]).Domain.Value
                return $result
            }
            
            # Case: NT Account
            if ($Name -like "*\*") {
                $domain, $user = $Name -split '\\'
                $result.Username = $user
                $result.Type = 'NT'
                $result.Domain = $domain
                return $result
            }
            
            # Case: SamAccountName
            $result.Username = $Name
            $result.Type = 'SAM'
            $result
        }
        
        function New-Entity {
            [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
            [CmdletBinding()]
            param (
                [string]
                $Name,
                
                [string]
                $SID,
                
                [string]
                $Domain
            )
            [PSCustomObject]@{
                Name   = $Name
                SID    = $SID
                Domain = $Domain
            }
        }
        #endregion Utility Functions
    }
    process {
        $resolvedName = ConvertFrom-Name -Name $Name
        if ($resolvedName.Type -eq 'SID') {
            New-Entity -Name $resolvedName.Username -SID $resolvedName.SID -Domain $resolvedName.Domain
            return
        }
        
        if ($resolvedName.Type -eq 'DN') {
            $adObject = Get-LdapObject -LdapFilter "(distinguishedName=$($resolvedName.Username))" -Server $resolvedName.Domain -Property ObjectSID, SamAccountName
        }
        else {
            $domains = Get-PSFTaskEngineCache -Module Roles -Name DomainCache | Sort-Object { $_.DNSRoot.Length }
            if ($resolvedName.Type -eq 'NT') { $domains = $domains | Where-Object NetBIOSName -EQ $resolvedName.Domain }
            if ($resolvedName.Type -eq 'UPN') {
                $domains = do {
                    $domains | Where-Object DNSRoot -EQ $resolvedName.Domain
                    $domains | Where-Object DNSRoot -Ne $resolvedName.Domain
                }
                while ($false)
            }
            if ($resolvedName.Type -eq 'SAM') {
                $domains = do {
                    $domains | Where-Object DNSRoot -EQ $env:USERDNSDOMAIN
                    $domains | Where-Object DNSRoot -Ne $env:USERDNSDOMAIN
                }
                while ($false)
            }
            $adObject = $null
            foreach ($domain in $domains) {
                $adObject = Get-LdapObject -LdapFilter "(samAccountName=$($resolvedName.Username))" -Server $domain.DNSRoot -Property ObjectSID, SamAccountName
                if ($adObject) {
                    $resolvedName.Domain = $domain.DNSRoot
                    break
                }
            }
        }
        if (-not $adObject) { throw "AD Object not found: $($Name)" }
        
        New-Entity -Name $adObject.SamAccountName -SID $adObject.ObjectSID -Domain $resolvedName.Domain
    }
}

function Add-RoleMember {
<#
    .SYNOPSIS
        Adds a role or a principal to the target role.
     
    .DESCRIPTION
        Adds a role or an Active Directory principal to the target role.
     
        Note: Requires elevation unless overridden using the 'Roles.Validation.SkipElevationTest' configuration.
     
    .PARAMETER Role
        The role to add a member to.
     
    .PARAMETER RoleMember
        The other role to include.
        Role must exist, circular membership is not checked for at this time.
     
    .PARAMETER ADMember
        The Active Directory member to include.
        Accepts UPN, DistinguishedName, SamAccountName, SID, NT Account or SamAccountName.
        Everything but SID is resolved first, identifiers that do not clarify domain will first resolve local domain, then the rest of the forest starting at the root.
        Use SID to specify builtin identities or users from foreign forests.
     
    .PARAMETER System
        The role system to work with.
        Use "Select-RoleSystem" to pick a default role.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .EXAMPLE
        PS C:\> Add-RoleMember -Role 'VMManagement' -RoleMember 'admins'
     
        Adds the role "admins" as member in role "VMManagement"
     
    .EXAMPLE
        PS C:\> Add-RoleMember -Role VMManagement -ADMember contoso\r-s-vm-management
     
        Adds the principal (presumably a group) "r-s-vm-management" from the domain "contoso" to the role "VMManagement"
#>

    [CmdletBinding(SupportsShouldProcess = $true)]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [PsfArgumentCompleter('Roles.Role')]
        [Alias('Name')]
        [string]
        $Role,
        
        [Parameter(Mandatory = $true, ParameterSetName = 'role')]
        [PsfArgumentCompleter('Roles.Role')]
        [string[]]
        $RoleMember,
        
        [Parameter(Mandatory = $true, ParameterSetName = 'ad')]
        [string[]]
        $ADMember,
        
        [PsfArgumentCompleter('Roles.System')]
        [string]
        $System = $script:selectedSystem
    )
    
    begin {
        Assert-Elevation -Cmdlet $PSCmdlet
        Assert-RoleSystem -System $System -Cmdlet $PSCmdlet
    }
    process {
        Assert-RoleRole -System $System -Role $Role -Cmdlet $PSCmdlet
        $mainRolePath = Get-RolePath -Role $Role -System $System
        
        #region Adding by Rolename
        foreach ($roleName in $RoleMember) {
            $rolePath = Get-RolePath -Role $roleName -System $System
            if (Test-Path -Path $rolePath) {
                Invoke-PSFProtectedCommand -ActionString 'Add-RoleMember.Adding.Role' -ActionStringValues $Role, $roleName -Target $Role -Tag add, role -ScriptBlock {
                    Invoke-MutexCommand -Name "PS.Roles.$System.$Role" -ErrorMessage "Failed to acquire file access lock" -ScriptBlock {
                        $roleData = Get-Content -Path $mainRolePath -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
                        if ($roleData.RoleMembers -notcontains $roleName) {
                            $roleData.RoleMembers = @($roleData.RoleMembers) + @($roleName)
                            $roleData | ConvertTo-Json -Depth 99 | Set-Content $mainRolePath -Encoding UTF8 -ErrorAction Stop
                        }
                    }
                } -Continue -EnableException $true -PSCmdlet $PSCmdlet
            }
            else {
                Write-PSFMessage -Level Warning -String 'Add-RoleMember.Unknown.MemberRole' -StringValues $Role, $System, $roleName
                Write-Error ($script:strings.'Add-RoleMember.Unknown.MemberRole' -f $Role, $System, $roleName)
            }
        }
        #endregion Adding by Rolename
        
        #region Adding Active Directory Entities
        foreach ($adEntity in $ADMember) {
            try { $resolvedIdentity = Resolve-ADEntity -Name $adEntity }
            catch {
                Write-PSFMessage -Level Warning -String 'Add-RoleMember.ADIdentity.Unknown' -StringValues $adEntity -ErrorRecord $_ -EnableException $true -PSCmdlet $PSCmdlet
                continue
            }
            Invoke-PSFProtectedCommand -ActionString 'Add-RoleMember.Adding.ADEntity' -ActionStringValues $Role, $resolvedIdentity.SamAccountName, $resolvedIdentity.SID -Target $Role -Tag add, adentity -ScriptBlock {
                Invoke-MutexCommand -Name "PS.Roles.$System.$Role" -ErrorMessage "Failed to acquire file access lock" -ScriptBlock {
                    $roleData = Get-Content -Path $mainRolePath -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
                    if ($roleData.ADMembers.SID -notcontains $resolvedIdentity.SID) {
                        $roleData.ADMembers = @($roleData.ADMembers) + @($resolvedIdentity)
                        $roleData | ConvertTo-Json -Depth 99 | Set-Content $mainRolePath -Encoding UTF8 -ErrorAction Stop
                    }
                }
            } -Continue -EnableException $true -PSCmdlet $PSCmdlet
        }
        #endregion Adding Active Directory Entities
    }
}


function Get-RoleMember {
<#
    .SYNOPSIS
        Get the role members of the specified role.
     
    .DESCRIPTION
        Get the role members of the specified role.
     
    .PARAMETER Role
        Name of the role to get the members of.
     
    .PARAMETER System
        The role system to work with.
        Use "Select-RoleSystem" to pick a default role.
     
    .EXAMPLE
        PS C:\> Get-RoleMember -Role 'VMManagement'
     
        Get all members of the role 'VMManagement'
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [PsfArgumentCompleter('Roles.Role')]
        [Alias('Name')]
        [string]
        $Role,
        
        [PsfArgumentCompleter('Roles.System')]
        [string]
        $System = $script:selectedSystem
    )
    
    begin {
        Assert-RoleSystem -System $System -Cmdlet $PSCmdlet
    }
    process {
        Assert-RoleRole -System $System -Role $Role -Cmdlet $PSCmdlet
        $rolePath = Get-RolePath -Role $Role -System $System
        
        try {
            $roleData = Invoke-MutexCommand -Name "PS.Roles.$System.$Role" -ErrorMessage "Failed to acquire file access lock" -ScriptBlock {
                Get-Content -Path $rolePath -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
            }
        }
        catch { throw }
        foreach ($roleMember in $roleData.RoleMembers) {
            [PSCustomObject]@{
                PSTypeName = 'Roles.RoleMember'
                Type       = "Role"
                Role       = $Role
                Name       = $roleMember
                SID           = $null
                Domain       = $null
            }
        }
        foreach ($adMember in $roleData.ADMembers) {
            [PSCustomObject]@{
                PSTypeName = 'Roles.RoleMember'
                Type       = "ADIdentity"
                Role       = $Role
                Name       = $adMember.Name
                SID           = $adMember.SID
                Domain       = $adMember.Domain
            }
        }
    }
}

function Remove-RoleMember {
<#
    .SYNOPSIS
        Removes a member from a role.
     
    .DESCRIPTION
        Removes a member from a role.
        Members can be both active directory entities or other roles.
     
        Note: Requires elevation unless overridden using the 'Roles.Validation.SkipElevationTest' configuration.
     
    .PARAMETER Role
        The role to remove from.
     
    .PARAMETER RoleMember
        Name of another role that should have its membership in -Role revoked.
     
    .PARAMETER ADMember
        SID of an active directory principal that should have its membership in -Role revoked.
     
    .PARAMETER System
        The role system to work with.
        Use "Select-RoleSystem" to pick a default role.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .EXAMPLE
        PS C:\> Get-RoleMember -Role VMManagement | Remove-RoleMember
     
        Clears all members from the role VMManagement.
     
    .EXAMPLE
        PS C:\> Remove-RoleMember -Role VMManagement -RoleMember admins
     
        Removes the role "admins" from the role "VMManagement"
#>

    [CmdletBinding(SupportsShouldProcess = $true)]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [PsfArgumentCompleter('Roles.Role')]
        [string]
        $Role,
        
        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [PsfArgumentCompleter('Roles.RoleMember')]
        [Alias('Name')]
        [string[]]
        $RoleMember,
        
        [Parameter(ValueFromPipelineByPropertyName = $true)]
        [PsfArgumentCompleter('Roles.ADMember')]
        [AllowEmptyString()]
        [AllowNull()]
        [Alias('SID')]
        [string[]]
        $ADMember,
        
        [PsfArgumentCompleter('Roles.System')]
        [string]
        $System = $script:selectedSystem
    )
    
    begin {
        Assert-Elevation -Cmdlet $PSCmdlet
        Assert-RoleSystem -System $System -Cmdlet $PSCmdlet
    }
    process {
        Assert-RoleRole -System $System -Role $Role -Cmdlet $PSCmdlet
        $allMembers = Get-RoleMember -Role $Role -System $System
        $mainRolePath = Get-RolePath -Role $Role -System $System
        
        foreach ($roleName in $RoleMember) {
            if (($allMembers | Where-Object Type -EQ Role).Name -notcontains $roleName) { continue }
            
            Invoke-PSFProtectedCommand -ActionString 'Remove-RoleMember.Removing.Role' -ActionStringValues $Role, $System, $roleName -Target $Role -Tag remove, role -ScriptBlock {
                Invoke-MutexCommand -Name "PS.Roles.$System.$Role" -ErrorMessage "Failed to acquire file access lock" -ScriptBlock {
                    $roleData = Get-Content -Path $mainRolePath -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
                    $roleData.RoleMembers = $roleData.RoleMembers | Where-Object { $_ -ne $roleName }
                    $roleData | ConvertTo-Json -Depth 99 | Set-Content $mainRolePath -Encoding UTF8 -ErrorAction Stop
                }
            } -Continue -EnableException $true -PSCmdlet $PSCmdlet
        }
        foreach ($adIdentifier in $ADMember) {
            if (-not $adIdentifier) { continue }
            if (($allMembers | Where-Object Type -EQ ADIdentity).SID -notcontains $adIdentifier) { continue }
            
            $memberObject = $allMembers | Where-Object Type -EQ ADIdentity | Where-Object SID -EQ $adIdentifier
            Invoke-PSFProtectedCommand -ActionString 'Remove-RoleMember.Removing.ADIdentity' -ActionStringValues $Role, $System, $memberObject.Name, $memberObject.Domain, $memberObject.SID -Target $Role -Tag remove, role -ScriptBlock {
                Invoke-MutexCommand -Name "PS.Roles.$System.$Role" -ErrorMessage "Failed to acquire file access lock" -ScriptBlock {
                    $roleData = Get-Content -Path $mainRolePath -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
                    $roleData.ADMembers = $roleData.ADMembers | Where-Object SID -NE $adIdentifier
                    $roleData | ConvertTo-Json -Depth 99 | Set-Content $mainRolePath -Encoding UTF8 -ErrorAction Stop
                }
            } -Continue -EnableException $true -PSCmdlet $PSCmdlet
        }
    }
}


function Test-RoleMembership {
<#
    .SYNOPSIS
        Test whether the current identity is in a given role.
     
    .DESCRIPTION
        Test whether the current identity is in a given role.
        Will either test the current user or the remote user if in a remoting session.
     
    .PARAMETER Role
        Name of the role to test against.
     
    .PARAMETER Local
        Do not use the remote identity.
        By default - unless overridden - this test will check the remote identity when used in PSRemoting session such as JEA.
        Override the defaults using the 'Roles.Roles.UseRemoteIdentity' configuration setting.
     
    .PARAMETER System
        The role system to work with.
        Use "Select-RoleSystem" to pick a default role.
     
    .EXAMPLE
        PS C:\> Test-RoleMembership -Role 'admins'
     
        Checks whether the current user is member of the admins role.
#>

    [OutputType([bool])]
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [PsfArgumentCompleter('Roles.RoleMember')]
        [Alias('Name')]
        [string]
        $Role,
        
        [switch]
        $Local,
        
        [PsfArgumentCompleter('Roles.System')]
        [string]
        $System = $script:selectedSystem
    )
    
    begin {
        Assert-RoleSystem -System $System -Cmdlet $PSCmdlet
        Assert-RoleRole -System $System -Role $Role -Cmdlet $PSCmdlet
        
        #region Utility Functions
        function Get-MemberSID {
            [CmdletBinding()]
            param (
                [string]
                $Role,
                
                [string]
                $System
            )
            
            $roleObject = Get-Role -System $System -Name $Role
            $roleObject.ADMembers.SID
            foreach ($roleMember in $roleObject.RoleMembers) {
                Get-MemberSID -Role $roleMember -System $System
            }
        }
        #endregion Utility Functions
        
        $useRemote = Get-PSFConfigValue -FullName 'Roles.Roles.UseRemoteIdentity'
        if ($Local) { $useRemote = $false }
        if ($PSBoundParameters.ContainsKey('Local') -and -not $Local) { $useRemote = $true }
    }
    process {
        
        $memberSID = Get-MemberSID -Role $Role -System $System
        
        $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        if ($PSSenderInfo -and $useRemote) { $identity = $PSSenderInfo.UserInfo.WindowsIdentity }
        
        foreach ($sid in $memberSID) {
            if ($identity.Groups.Value -contains $sid) { return $true }
            if ($identity.User.Value -eq $sid) { return $true }
        }
        
        return $false
    }
}


function Get-Role {
    <#
        .SYNOPSIS
            Get a list of existing roles.
         
        .DESCRIPTION
            Get a list of existing roles.
         
        .PARAMETER Name
            The name of the roles to filter by.
         
        .PARAMETER System
            The role system to work with.
            Use "Select-RoleSystem" to pick a default role.
         
        .EXAMPLE
            PS C:\> Get-Role
     
            Get a list of all existing roles in the currently selected role system.
    #>

    [CmdletBinding()]
    param (
        [PsfArgumentCompleter('Roles.Name')]
        [string]
        $Name = '*',
        
        [PsfArgumentCompleter('Roles.System')]
        [string]
        $System = $script:selectedSystem
    )
    
    begin {
        Assert-RoleSystem -System $System -Cmdlet $PSCmdlet
    }
    process {
        $systemPath = Get-RoleSystemPath -System $System
        foreach ($file in Get-ChildItem -Path $systemPath -File) {
            $systemName = $file.Name | ConvertFrom-Base64 -ErrorAction Ignore
            if (-not $systemName) {
                Write-PSFMessage -Level Warning -String 'Get-Role.BadFileName' -StringValues $file.Name, $System -Once "Roles.Role.$($file.Name)"
                continue
            }
            if ($systemName -notlike $Name) { continue }
            
            try {
                Invoke-MutexCommand -Name "PS.Roles.$System.$systemName" -ErrorMessage "Failed to acquire file access lock" -ScriptBlock {
                    Get-Content -Path $file.FullName -Encoding UTF8 -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
                }
            }
            catch {
                Write-PSFMessage -String 'Get-Role.File.AccessError' -StringValues $systemName, $file.FullName, $System -EnableException $true -ErrorRecord $_ -PSCmdlet $PSCmdlet
                continue
            }
        }
    }
}

function New-Role {
<#
    .SYNOPSIS
        Create a new role.
     
    .DESCRIPTION
        Create a new role.
        Roles can be granted permission upon and membership to.
         
        Note: Requires elevation unless overridden using the 'Roles.Validation.SkipElevationTest' configuration.
     
    .PARAMETER Name
        Name of the role to create.
     
    .PARAMETER Description
        Description of the role being created.
     
    .PARAMETER Force
        Recreate a role if it has already been created.
        Recreating a role will remove all previously assigned memberships.
        By default, this command fails if the role specified already exists.
     
    .PARAMETER System
        The role system to work with.
        Use "Select-RoleSystem" to pick a default role.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .EXAMPLE
        PS C:\> New-Role -Name 'admins' -Description 'administrative access over the configuration deployment system'
     
        Create a new role named "admins".
#>

    [CmdletBinding(SupportsShouldProcess = $true)]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $Name,
        
        [Parameter(Mandatory = $true)]
        [string]
        $Description,
        
        [switch]
        $Force,
        
        [PsfArgumentCompleter('Roles.System')]
        [string]
        $System = $script:selectedSystem
    )
    
    begin {
        Assert-Elevation -Cmdlet $PSCmdlet
        Assert-RoleSystem -System $System -Cmdlet $PSCmdlet
    }
    process {
        $rolePath = Get-RolePath -Role $Name -System $System
        if (-not $Force -and (Test-Path -Path $rolePath)) {
            Stop-PSFFunction -String 'New-Role.ExistsAlready' -StringValues $Name, $System -EnableException $true -Category InvalidArgument -Cmdlet $PSCmdlet
        }
        
        $roleData = [pscustomobject]@{
            Name        = $Name
            Description = $Description
            System        = $System
            RoleMembers = @()
            ADMembers   = @()
        }
        Invoke-PSFProtectedCommand -ActionString 'New-Role.Create' -ActionStringValues $Name, $System -ScriptBlock {
            Invoke-MutexCommand -Name "PS.Roles.$System.$Name" -ErrorMessage "Failed to acquire file access lock" -ScriptBlock {
                $roleData | ConvertTo-Json -Depth 3 | Set-Content $rolePath -Encoding UTF8 -ErrorAction Stop
            }
        } -Target $Name -EnableException $true -PSCmdlet $PSCmdlet
    }
}

function Remove-Role {
<#
    .SYNOPSIS
        Remove a defined role.
     
    .DESCRIPTION
        Remove a defined role.
        Will silently continue if the specified role does not exist.
     
        Note: Requires elevation unless overridden using the 'Roles.Validation.SkipElevationTest' configuration.
     
    .PARAMETER Name
        Name of the role to remove.
     
    .PARAMETER System
        The role system to work with.
        Use "Select-RoleSystem" to pick a default role.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .EXAMPLE
        PS C:\> Remove-Role -Name 'admins'
     
        Removes the "admins" role
     
    .EXAMPLE
        PS C:\> Get-Role | Remove-Role
     
        Removes all roles of the current system
#>

    [CmdletBinding(SupportsShouldProcess = $true)]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [PsfArgumentCompleter('Roles.Name')]
        [string[]]
        $Name,
        
        [PsfArgumentCompleter('Roles.System')]
        [string]
        $System = $script:selectedSystem
    )
    
    begin {
        Assert-Elevation -Cmdlet $PSCmdlet
        Assert-RoleSystem -System $System -Cmdlet $PSCmdlet
    }
    process {
        foreach ($nameEntry in $Name) {
            $systemPath = Get-RolePath -Role $nameEntry -System $System
            if (-not (Test-Path -Path $systemPath)) { continue }
            
            Invoke-PSFProtectedCommand -ActionString 'Remove-Role.Removing' -ActionStringValues $nameEntry, $System -ScriptBlock {
                Invoke-MutexCommand -Name "PS.Roles.$System.$nameEntry" -ErrorMessage "Failed to acquire file access lock" -ScriptBlock {
                    Remove-Item -Path $systemPath -Force -ErrorAction Stop
                } -ErrorAction Stop
            } -Target $nameEntry -EnableException $true -PSCmdlet $PSCmdlet
        }
    }
}

function Set-Role {
<#
    .SYNOPSIS
        Update the description of an existing role.
     
    .DESCRIPTION
        Update the description of an existing role.
     
        Note: Requires elevation unless overridden using the 'Roles.Validation.SkipElevationTest' configuration.
     
    .PARAMETER Name
        Name of the role to update.
     
    .PARAMETER Description
        Description to apply.
     
    .PARAMETER System
        The role system to work with.
        Use "Select-RoleSystem" to pick a default role.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .EXAMPLE
        PS C:\> Set-Role -Name 'VMOperators' -Description 'Operators allowed to manage Virtual Machine state'
     
        Updates the description of the VMOperators role
#>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')]
    [CmdletBinding(SupportsShouldProcess = $true)]
    param (
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [Alias('Role')]
        [string]
        $Name,
        
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [string]
        $Description,
        
        [PsfArgumentCompleter('Roles.System')]
        [string]
        $System = $script:selectedSystem
    )
    
    begin {
        Assert-Elevation -Cmdlet $PSCmdlet
        Assert-RoleSystem -System $System -Cmdlet $PSCmdlet
    }
    process {
        Assert-RoleRole -System $System -Role $Name -Cmdlet $PSCmdlet
        $systemPath = Get-RolePath -Role $Name -System $System
        if (-not (Test-Path -Path $systemPath)) {
            Stop-PSFFunction -String 'Set-Role.Role.NotFound' -StringValues $Name, $System -EnableException $true -Category ObjectNotFound -Cmdlet $PSCmdlet
        }
        
        Invoke-PSFProtectedCommand -ActionString 'Set-Role.Updating' -ActionStringValues $Name, $System -ScriptBlock {
            Invoke-MutexCommand -Name "PS.Roles.$System.$Name" -ErrorMessage "Failed to acquire file access lock" -ScriptBlock {
                $datum = Get-Content -Path $systemPath -Encoding UTF8 -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
                $datum.Description = $Description
                $datum | ConvertTo-Json -Depth 99 -ErrorAction Stop | Set-Content -Path $systemPath -Encoding UTF8 -ErrorAction Stop
            }
        } -Target $Name -EnableException $true -PSCmdlet $PSCmdlet
    }
}

function Get-RoleSystem {
<#
    .SYNOPSIS
        Get a list of available role systems.
     
    .DESCRIPTION
        Get a list of available role systems.
     
    .PARAMETER Name
        Name of the systems to filter by.
        Defaults to '*'
     
    .EXAMPLE
        PS C:\> Get-RoleSystem
     
        Get a list of all available role systems.
#>

    [CmdletBinding()]
    param (
        [PsfArgumentCompleter('Roles.System')]
        [string]
        $Name = '*'
    )
    
    process {
        if (-not (Test-Path $script:roleSystemPath)) { return }
        
        foreach ($folder in Get-ChildItem -Path $script:roleSystemPath -Directory) {
            $systemName = $folder.Name | ConvertFrom-Base64 -ErrorAction Ignore
            if (-not $systemName) {
                Write-PSFMessage -Level Warning -String 'Get-RoleSystem.BadFolderName' -StringValues $folder.Name -Once "Roles.System.$($folder.Name)"
                continue
            }
            if ($systemName -notlike $Name) { continue }
            
            [pscustomobject]@{
                Name  = $systemName
                Roles = (Get-ChildItem -Path $folder.FullName -File | Microsoft.PowerShell.Utility\Select-Object -ExpandProperty BaseName | ConvertFrom-Base64 -ErrorAction Ignore | Measure-Object).Count
                CreatedOn = $folder.CreationTime
                Modified = (Get-ChildItem -Path $folder.FullName -File | Sort-Object LastWriteTime -Descending | Microsoft.PowerShell.Utility\Select-Object -First 1).LastWriteTime
            }
        }
    }
}


function New-RoleSystem {
<#
    .SYNOPSIS
        Create a new role system.
     
    .DESCRIPTION
        Create a new role system.
        A role system is a container for roles and rule assignments.
         
        Note: Requires elevation unless overridden using the 'Roles.Validation.SkipElevationTest' configuration.
     
    .PARAMETER Name
        Name of the role system to create.
     
    .PARAMETER Force
        Overwrite existing role systems.
        By default, this command will fail if a role system of the specified name already exists.
        Overwriting an existing role system will remove all previously existing content (roles & role memberships)
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .EXAMPLE
        PS C:\> New-RoleSystem -Name 'VMDeployment'
     
        Create a new role system named "VMDeployment"
#>

    [CmdletBinding(SupportsShouldProcess = $true)]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $Name,
        
        [switch]
        $Force
    )
    
    begin {
        Assert-Elevation -Cmdlet $PSCmdlet
    }
    process {
        $systemFolder = Get-RoleSystemPath -System $Name
        if (Test-Path -Path $systemFolder) {
            if ($Force) {
                Invoke-PSFProtectedCommand -ActionString 'New-RoleSystem.ClearingPrevious' -ActionStringValues $Name -ScriptBlock {
                    Remove-Item -Path $systemFolder -Force -Recurse -ErrorAction Stop
                } -Target $Name -EnableException $true -PSCmdlet $PSCmdlet
            }
            else {
                Stop-PSFFunction -String 'New-RoleSystem.ExistsAlready' -StringValues $Name -EnableException $true -Cmdlet $PSCmdlet -Category InvalidArgument
            }
        }
        
        Invoke-PSFProtectedCommand -ActionString 'New-RoleSystem.Creating' -ActionStringValues $Name -Target $Name -ScriptBlock {
            $null = New-Item -Path $systemFolder -ItemType Directory -Force -ErrorAction Stop
        } -EnableException $true -PSCmdlet $PSCmdlet
    }
}


function Remove-RoleSystem {
<#
    .SYNOPSIS
        Remove an existing role system.
     
    .DESCRIPTION
        Remove an existing role system.
        Will silently terminate if system is unknown.
     
        Note: Requires elevation unless overridden using the 'Roles.Validation.SkipElevationTest' configuration.
     
    .PARAMETER Name
        Name of the role system to delete.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .EXAMPLE
        PS C:\> Remove-RoleSystem -Name 'VMDeployment'
     
        Removes the role system "VMDeployment"
#>

    [CmdletBinding(SupportsShouldProcess = $true)]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [PsfArgumentCompleter('Roles.System')]
        [string[]]
        $Name
    )
    
    begin {
        Assert-Elevation -Cmdlet $PSCmdlet
    }
    process {
        if (-not (Test-Path $script:roleSystemPath)) { return }
        
        foreach ($systemName in $Name) {
            $systemPath = Get-RoleSystemPath -System $systemName
            
            if (-not (Test-Path -Path $systemPath)) { continue }
            
            Invoke-PSFProtectedCommand -ActionString 'Remove-RoleSystem.Removing' -ActionStringValues $systemName -ScriptBlock {
                Remove-Item -Path $systemPath -Force -Recurse -ErrorAction Stop
            } -Target $systemName -EnableException $true -PSCmdlet $PSCmdlet
        }
    }
}


function Select-RoleSystem {
<#
    .SYNOPSIS
        Select the default role system to use.
     
    .DESCRIPTION
        Select the default role system to use.
     
    .PARAMETER Name
        The name of the system to use.
     
    .EXAMPLE
        PS C:\> Select-RoleSystem -Name 'VMDeployment'
     
        Selects the 'VMDeployment' roles system as the default system.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [PsfArgumentCompleter('Roles.System')]
        [string]
        $Name
    )
    
    process {
        $system = Get-RoleSystem | Where-Object Name -EQ $Name
        if (-not $system) {
            Stop-PSFFunction -String 'Select-RoleSystem.NotFound' -StringValues $Name -EnableException $true -Category ObjectNotFound -Cmdlet $PSCmdlet
        }
        
        $script:selectedSystem = $system.Name
    }
}


<#
This is an example configuration file
 
By default, it is enough to have a single one of them,
however if you have enough configuration settings to justify having multiple copies of it,
feel totally free to split them into multiple files.
#>


<#
# Example Configuration
Set-PSFConfig -Module 'Roles' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'"
#>


Set-PSFConfig -Module 'Roles' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging."
Set-PSFConfig -Module 'Roles' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments."

Set-PSFConfig -Module 'Roles' -Name 'Validation.SkipElevationTest' -Value $false -Initialize -Validation 'bool' -Description 'Disables the check for elevation. By default, Roles will check whether the current process is ran as administrator before allowing write operations. This may be undesireable for JEA endpoints running under gMSA which have had permissions delegated to the roles folder.'
Set-PSFConfig -Module 'Roles' -Name 'Roles.UseRemoteIdentity' -Value $true -Initialize -Validation 'bool' -Description 'Whether Test-RoleMembership uses the remote identity when called in a PSRemoting session.'

<#
Stored scriptblocks are available in [PsfValidateScript()] attributes.
This makes it easier to centrally provide the same scriptblock multiple times,
without having to maintain it in separate locations.
 
It also prevents lengthy validation scriptblocks from making your parameter block
hard to read.
 
Set-PSFScriptblock -Name 'Roles.ScriptBlockName' -Scriptblock {
     
}
#>


Register-PSFTeppScriptblock -Name 'Roles.Role' -ScriptBlock {
    (Get-Role).Name
}
Register-PSFTeppScriptblock -Name 'Roles.RoleMember' -ScriptBlock {
    if (-not $fakeBoundParameters.Name) {
        return (Get-Role).Name
    }
    
    $localSystem = $script:selectedSystem
    if ($fakeBoundParameters.System) { $localSystem = $fakeBoundParameters.System }
    (Get-RoleMember -Role $fakeBoundParameters.Name -System $localSystem | Where-Object Type -EQ 'Role').Name
}
Register-PSFTeppScriptblock -Name 'Roles.ADMember' -ScriptBlock {
    if (-not $fakeBoundParameters.Name) { return }
    
    $localSystem = $script:selectedSystem
    if ($fakeBoundParameters.System) { $localSystem = $fakeBoundParameters.System }
    (Get-RoleMember -Role $fakeBoundParameters.Name -System $localSystem | Where-Object Type -EQ 'ADIdentity').Name
}

Register-PSFTeppScriptblock -Name 'Roles.System' -ScriptBlock {
    (Get-RoleSystem).Name
}

<#
# Example:
Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name Roles.alcohol
#>


# Path to central folder managing roles
$script:roleSystemPath = Join-Path -Path ([System.Environment]::GetFolderPath("CommonApplicationData")) -ChildPath 'PowerShell/Roles'

# Selected system - used as default for all role and rolemember commands
$script:selectedSystem = ''

# Localized Strings for Write-Error calls
$script:strings = Get-PSFLocalizedString -Module Roles

# Used in the module for capital-casing LDAP properties. Consumed by Get-LdapObject
$script:culture = Get-Culture

if (-not (Test-Path -Path $script:roleSystemPath)) {
    $null = New-Item -Path $script:roleSystemPath -ItemType Directory -Force -ErrorAction Ignore
}

Set-PSFTaskEngineCache -Module Roles -Name DomainCache -Lifetime 24h -Collector {
    $roles = Get-Module Roles
    if (-not $roles) {
        Import-Module Roles
        $roles = Get-Module Roles
    }
    & $roles {
        $forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
        $partitions = $forest.Schema.Name -replace '^CN=Schema', 'CN=Partitions'
        Get-LdapObject -SearchRoot $partitions -LdapFilter '(netBiosName=*)'
    }
}

Set-MutexDefault -Access admins

New-PSFLicense -Product 'Roles' -Manufacturer 'Friedrich Weinmann' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2021-04-08") -Text @"
Copyright (c) 2021 Friedrich Weinmann
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"@

#endregion Load compiled code