$domain = 'cascades.local'
$gpoName = 'CSC - Folder Redirection'

# Security filter: remove Authenticated Users, add zachary.nelson
$gpo = Get-GPO -Name $gpoName -Domain $domain
Write-Output "GPO: $($gpo.DisplayName) — $($gpo.Id)"

# Remove Authenticated Users from Security Filtering
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)"
}

# Grant zachary.nelson Apply Group Policy permission
try {
    Set-GPPermission -Name $gpoName -Domain $domain -PermissionLevel GpoApply -TargetName 'zachary.nelson' -TargetType User -EA Stop
    Write-Output "[OK] Added zachary.nelson with GpoApply"
} catch {
    Write-Output "[ERROR] Add zachary.nelson: $($_.Exception.Message)"
}

# Also ensure Domain Admins can still read/edit the GPO
try {
    Set-GPPermission -Name $gpoName -Domain $domain -PermissionLevel GpoEditDeleteModifySecurity -TargetName 'Domain Admins' -TargetType Group -EA Stop
    Write-Output "[OK] Domain Admins GpoEditDeleteModifySecurity confirmed"
} catch {
    Write-Output "[WARN] Domain Admins: $($_.Exception.Message)"
}

# Link GPO to OU=Administrative
$ouDN = 'OU=Administrative,OU=Departments,DC=cascades,DC=local'
try {
    $link = New-GPLink -Name $gpoName -Domain $domain -Target $ouDN -LinkEnabled Yes -EA Stop
    Write-Output "[OK] Linked to $ouDN"
} catch {
    if ($_.Exception.Message -like '*already exists*') {
        Write-Output "[INFO] Link already exists — enabling it"
        Set-GPLink -Name $gpoName -Domain $domain -Target $ouDN -LinkEnabled Yes -EA SilentlyContinue
        Write-Output "[OK] Link enabled"
    } else {
        Write-Output "[ERROR] Link: $($_.Exception.Message)"
    }
}

Write-Output ""
Write-Output "=== GPO Scope after changes ==="
Get-GPPermission -Name $gpoName -Domain $domain -All | ForEach-Object {
    Write-Output "  $($_.Trustee.Name) — $($_.Permission)"
}
Write-Output ""
Write-Output "=== GPO Links ==="
(Get-GPO -Name $gpoName -Domain $domain).GpoLinks | ForEach-Object {
    Write-Output "  $($_.SomName) — Enabled: $($_.Enabled)"
}
