$homesPath = 'D:\Homes'
$allow = [System.Security.AccessControl.AccessControlType]::Allow

Write-Output "=== Fixing homes root ACL ==="

$acl = Get-Acl $homesPath

# Remove all BUILTIN\Users entries (these inherit down to subfolders — that's the bug)
$removed = 0
$acl.Access | Where-Object { $_.IdentityReference.Value -eq 'BUILTIN\Users' } | ForEach-Object {
    $acl.RemoveAccessRule($_) | Out-Null
    $removed++
}
Write-Output "Removed $removed BUILTIN\Users rule(s) from root"

# Add back minimum: Authenticated Users, This Folder Only — list + create folders
$minRule = New-Object System.Security.AccessControl.FileSystemAccessRule(
    'Authenticated Users',
    [System.Security.AccessControl.FileSystemRights]'ReadAndExecute,Synchronize,CreateDirectories',
    [System.Security.AccessControl.InheritanceFlags]::None,
    [System.Security.AccessControl.PropagationFlags]::None,
    $allow
)
$acl.AddAccessRule($minRule)
Set-Acl -Path $homesPath -AclObject $acl
Write-Output "[OK] Root: Authenticated Users — This Folder Only (list + create folders)"

Write-Output ""
Write-Output "=== Fixing user subfolder ACLs ==="
Get-ChildItem $homesPath -Directory -EA SilentlyContinue | ForEach-Object {
    $folder = $_.FullName
    $name   = $_.Name

    $subAcl = Get-Acl $folder

    # Break inheritance — copy existing ACEs explicitly (no longer inherit from root)
    $subAcl.SetAccessRuleProtection($true, $true)
    Set-Acl -Path $folder -AclObject $subAcl
    $subAcl = Get-Acl $folder

    # Remove BUILTIN\Users entries that came from root inheritance
    $count = 0
    $subAcl.Access | Where-Object { $_.IdentityReference.Value -eq 'BUILTIN\Users' } | ForEach-Object {
        $subAcl.RemoveAccessRule($_) | Out-Null
        $count++
    }
    Set-Acl -Path $folder -AclObject $subAcl
    Write-Output "  [$name] Removed $count BUILTIN\Users rule(s), inheritance disabled [OK]"
}

Write-Output ""
Write-Output "=== Verification — root ACL ==="
(Get-Acl $homesPath).Access | ForEach-Object {
    Write-Output "  $($_.IdentityReference) | $($_.FileSystemRights) | Inherit:$($_.InheritanceFlags)"
}

Write-Output ""
Write-Output "=== Verification — subfolder ACLs ==="
Get-ChildItem $homesPath -Directory -EA SilentlyContinue | ForEach-Object {
    Write-Output "  --- $($_.Name) ---"
    (Get-Acl $_.FullName).Access | ForEach-Object {
        Write-Output "    $($_.IdentityReference) | $($_.FileSystemRights) | Inherit:$($_.InheritanceFlags)"
    }
}
