$domain = 'cascades.local'
$gpoName = 'CSC - Folder Redirection'
$groupName = 'SG-FolderRedirect'
$groupOU = 'OU=Security Groups,OU=Groups,DC=cascades,DC=local'

Import-Module ActiveDirectory -EA SilentlyContinue

# --- Create SG-FolderRedirect if it doesn't exist ---
$grp = Get-ADGroup -Filter "Name -eq '$groupName'" -EA SilentlyContinue
if (-not $grp) {
    try {
        New-ADGroup -Name $groupName -GroupScope Global -GroupCategory Security `
            -Description 'Members receive GPO folder redirection to \\CS-SERVER\homes\%USERNAME%' `
            -Path $groupOU -EA Stop
        Write-Output "[OK] Created group: $groupName in $groupOU"
    } catch {
        # Try root of domain if OU doesn't exist
        try {
            New-ADGroup -Name $groupName -GroupScope Global -GroupCategory Security `
                -Description 'Members receive GPO folder redirection to \\CS-SERVER\homes\%USERNAME%' `
                -Path "CN=Users,DC=cascades,DC=local" -EA Stop
            Write-Output "[OK] Created group: $groupName in CN=Users (fallback)"
        } catch {
            Write-Output "[ERROR] Create group: $($_.Exception.Message)"
        }
    }
} else {
    Write-Output "[INFO] Group already exists: $($grp.DistinguishedName)"
}

# --- Add zachary.nelson to the group ---
try {
    Add-ADGroupMember -Identity $groupName -Members 'Zachary.Nelson' -EA Stop
    Write-Output "[OK] Added Zachary.Nelson to $groupName"
} catch {
    if ($_.Exception.Message -like '*already a member*') {
        Write-Output "[INFO] Zachary.Nelson already in $groupName"
    } else {
        Write-Output "[ERROR] Add member: $($_.Exception.Message)"
    }
}

# --- Remove Authenticated Users from GPO security filter ---
try {
    Set-GPPermission -Name $gpoName -Domain $domain `
        -PermissionLevel None -TargetName 'Authenticated Users' -TargetType Group -EA Stop
    Write-Output "[OK] Removed Authenticated Users from security filter"
} catch {
    Write-Output "[WARN] Remove Authenticated Users: $($_.Exception.Message)"
}

# --- Add SG-FolderRedirect with GpoApply ---
try {
    Set-GPPermission -Name $gpoName -Domain $domain `
        -PermissionLevel GpoApply -TargetName $groupName -TargetType Group -EA Stop
    Write-Output "[OK] Added $groupName with GpoApply"
} catch {
    Write-Output "[ERROR] Add group to GPO: $($_.Exception.Message)"
}

# --- Confirm final state ---
Write-Output ""
Write-Output "=== GPO Security Filter ==="
Get-GPPermission -Name $gpoName -Domain $domain -All | ForEach-Object {
    Write-Output "  $($_.Trustee.Name) [$($_.Trustee.TrusteeType)] — $($_.Permission)"
}

Write-Output ""
Write-Output "=== $groupName members ==="
Get-ADGroupMember -Identity $groupName -EA SilentlyContinue | ForEach-Object {
    Write-Output "  $($_.SamAccountName)"
}
