# Link "CSC - Caregiver Workstation" at OU=Caregivers and apply TEST security filtering.
# Auth Users -> Read only (MS16-072: computer must read user GPO). SG-Caregivers-Test -> Apply (pilot.test only).
# Go-live later: Set-GPPermission ... -TargetName 'SG-Caregivers' -PermissionLevel GpoApply ; remove the test group.
$ErrorActionPreference = 'Stop'
Import-Module GroupPolicy -ErrorAction Stop

$gpoName = 'CSC - Caregiver Workstation'
$target  = 'OU=Caregivers,OU=Departments,DC=cascades,DC=local'

# 1) Link (idempotent)
try {
  New-GPLink -Name $gpoName -Target $target -LinkEnabled Yes -ErrorAction Stop | Out-Null
  Write-Output ('LINKED at ' + $target)
} catch {
  if ($_.Exception.Message -match 'already linked|already exists') { Write-Output ('Already linked at ' + $target) }
  else { throw }
}

# 2) Security filtering: Auth Users -> Read, SG-Caregivers-Test -> Apply
Set-GPPermission -Name $gpoName -TargetName 'Authenticated Users' -TargetType Group -PermissionLevel GpoRead -Replace | Out-Null
Write-Output 'Authenticated Users -> GpoRead (read only)'
Set-GPPermission -Name $gpoName -TargetName 'SG-Caregivers-Test' -TargetType Group -PermissionLevel GpoApply | Out-Null
Write-Output 'SG-Caregivers-Test -> GpoApply'

# 3) Verify
Write-Output ''
Write-Output '===== VERIFY ====='
Write-Output '--- Permissions ---'
Get-GPPermission -Name $gpoName -All | ForEach-Object { '  ' + $_.Trustee.Name + ' : ' + $_.Permission }
Write-Output '--- Links on OU=Caregivers ---'
(Get-GPInheritance -Target $target).GpoLinks | ForEach-Object { '  ' + $_.DisplayName + ' | enabled=' + $_.Enabled + ' | enforced=' + $_.Enforced }
