Import-Module GroupPolicy -ErrorAction Stop
$ErrorActionPreference = 'Continue'
$domain = 'cascades.local'
$srv = 'CS-SERVER'
$sysvol = "\\$srv\SYSVOL\$domain\Policies"
$ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss"

Write-Output "=== 1. CSC - Printer Deployment ==="
if (-not (Get-GPO -Name 'CSC - Printer Deployment' -Domain $domain -ErrorAction SilentlyContinue)) {
    New-GPO -Name 'CSC - Printer Deployment' -Domain $domain `
        -Comment 'Phase 2.6: Deploy CS-SERVER shared printers with OU-based ILT. UNLINKED - link to OU=Workstations at Phase 3 cutover.' | Out-Null
    Write-Output "  [OK] GPO created"
} else { Write-Output "  [--] Already exists" }

$gpo = Get-GPO -Name 'CSC - Printer Deployment' -Domain $domain
$gpoPath = "$sysvol\{$($gpo.Id.ToString().ToUpper())}"
$pDir = "$gpoPath\User\Preferences\Printers"
New-Item -Path $pDir -ItemType Directory -Force | Out-Null

$printers = @(
    @{ Share='CopyRoom';       OUs=@() }
    @{ Share='BusinessOffice'; OUs=@('OU=Administrative,OU=Departments,DC=cascades,DC=local') }
    @{ Share='Accounting';     OUs=@('OU=Administrative,OU=Departments,DC=cascades,DC=local') }
    @{ Share='AdminOffice';    OUs=@('OU=Administrative,OU=Departments,DC=cascades,DC=local','OU=Resident Services,OU=Departments,DC=cascades,DC=local') }
    @{ Share='ExecDirector';   OUs=@('OU=Administrative,OU=Departments,DC=cascades,DC=local') }
    @{ Share='SalesMarketing'; OUs=@('OU=Marketing,OU=Departments,DC=cascades,DC=local') }
    @{ Share='Kitchen';        OUs=@('OU=Culinary,OU=Departments,DC=cascades,DC=local') }
    @{ Share='CulinaryChef';   OUs=@('OU=Culinary,OU=Departments,DC=cascades,DC=local') }
    @{ Share='FrontDesk';      OUs=@('OU=Resident Services,OU=Departments,DC=cascades,DC=local') }
    @{ Share='HealthServices'; OUs=@('OU=Care-Assisted Living,OU=Departments,DC=cascades,DC=local','OU=Care-Memorycare,OU=Departments,DC=cascades,DC=local') }
    @{ Share='LifeEnrichment'; OUs=@('OU=Life Enrichment,OU=Departments,DC=cascades,DC=local') }
    @{ Share='MCDirector';     OUs=@('OU=Care-Memorycare,OU=Departments,DC=cascades,DC=local') }
    @{ Share='MCMedTech';      OUs=@('OU=Caregivers,OU=Departments,DC=cascades,DC=local','OU=Care-Memorycare,OU=Departments,DC=cascades,DC=local') }
)

$sb = [System.Text.StringBuilder]::new()
[void]$sb.AppendLine('<?xml version="1.0" encoding="utf-8"?>')
[void]$sb.AppendLine('<Printers clsid="{1F577D12-3D1B-471c-A7BF-E0F49DC793FE}">')
foreach ($p in $printers) {
    $uid = [System.Guid]::NewGuid().ToString().ToUpper()
    $unc = "\\CS-SERVER\$($p.Share)"
    [void]$sb.AppendLine("  <SharedPrinter clsid=""{9A5E9697-9095-436d-A0EE-4D128FDFBCE5}"" name=""$unc"" status=""$unc"" image=""0"" changed=""$ts"" uid=""{$uid}"">")
    [void]$sb.AppendLine("    <Properties action=""U"" comment="""" path=""$unc"" location="""" default=""0"" skipLocal=""1"" deleteAll=""0"" persistent=""0"" deleteMaps=""0"" portName="""">")
    if ($p.OUs.Count -gt 0) {
        [void]$sb.AppendLine("      <Filters>")
        $first = $true
        foreach ($ou in $p.OUs) {
            $bool = if ($first) { 'AND' } else { 'OR' }
            [void]$sb.AppendLine("        <FilterOrgUnit bool=""$bool"" not=""0"" name=""LDAP://$ou"" userContext=""1"" directMember=""0""/>")
            $first = $false
        }
        [void]$sb.AppendLine("      </Filters>")
    } else {
        [void]$sb.AppendLine("      <Filters/>")
    }
    [void]$sb.AppendLine("    </Properties>")
    [void]$sb.AppendLine("  </SharedPrinter>")
}
[void]$sb.AppendLine("</Printers>")
[System.IO.File]::WriteAllText("$pDir\Printers.xml", $sb.ToString(), [System.Text.Encoding]::UTF8)
Write-Output "  [OK] Printers.xml written (13 printers with OU-based ILT)"

$iniPath = "$gpoPath\GPT.INI"
$raw = [System.IO.File]::ReadAllText($iniPath)
$ver = 0; if ($raw -match '(?m)^Version=(\d+)') { $ver = [int]$Matches[1] }
$uVer = (($ver -shr 16) -band 0xFFFF) + 1
$mVer = $ver -band 0xFFFF
$newVer = ($uVer -shl 16) -bor $mVer
$machExt = ''; if ($raw -match '(?m)^gPCMachineExtensionNames=([^\r\n]+)') { $machExt = $Matches[1] }
$ini = "[General]`r`nVersion=$newVer`r`n"
if ($machExt) { $ini += "gPCMachineExtensionNames=$machExt`r`n" }
$ini += "gPCUserExtensionNames=[{BC75B1ED-5833-4858-9BB8-CBF0B166DF9D}{D02B1F72-3407-48AE-BA88-E8213C6761F1}]`r`n"
[System.IO.File]::WriteAllText($iniPath, $ini, [System.Text.Encoding]::ASCII)
Write-Output "  [OK] GPT.INI updated"

Write-Output ""
Write-Output "=== 2. CSC - Drive Mappings ==="
if (-not (Get-GPO -Name 'CSC - Drive Mappings' -Domain $domain -ErrorAction SilentlyContinue)) {
    New-GPO -Name 'CSC - Drive Mappings' -Domain $domain `
        -Comment 'Phase 2.6: M: S: T: K: R: with group/OU ILT. UNLINKED - link to OU=Departments at Phase 3 cutover.' | Out-Null
    Write-Output "  [OK] GPO created"
} else { Write-Output "  [--] Already exists" }

$gpo = Get-GPO -Name 'CSC - Drive Mappings' -Domain $domain
$gpoPath = "$sysvol\{$($gpo.Id.ToString().ToUpper())}"
$dDir = "$gpoPath\User\Preferences\Drives"
New-Item -Path $dDir -ItemType Directory -Force | Out-Null

$drives = @(
    @{ Letter='M'; Share='\\CS-SERVER\Management';  Label='Management';   FType='Group'; FVal='CASCADES\SG-Mgmt-RW' }
    @{ Letter='S'; Share='\\CS-SERVER\Sales';        Label='Sales';        FType='Group'; FVal='CASCADES\SG-Sales-RW' }
    @{ Letter='T'; Share='\\CS-SERVER\Activities';   Label='Activities';   FType='Group'; FVal='CASCADES\SG-Activities-RW' }
    @{ Letter='K'; Share='\\CS-SERVER\Culinary';     Label='Culinary';     FType='OU';    FVal='OU=Culinary,OU=Departments,DC=cascades,DC=local' }
    @{ Letter='R'; Share='\\CS-SERVER\Receptionist'; Label='Receptionist'; FType='OU';    FVal='OU=Resident Services,OU=Departments,DC=cascades,DC=local' }
)

$sb2 = [System.Text.StringBuilder]::new()
[void]$sb2.AppendLine('<?xml version="1.0" encoding="utf-8"?>')
[void]$sb2.AppendLine('<Drives clsid="{8FDDCC1A-0C3C-43cd-A6B4-8A48251CB2FE}">')
foreach ($d in $drives) {
    $uid = [System.Guid]::NewGuid().ToString().ToUpper()
    [void]$sb2.AppendLine("  <Drive clsid=""{935D1B74-9CB8-4e3c-9914-7DD559B7A417}"" name=""$($d.Letter):"" status=""$($d.Letter):"" image=""2"" changed=""$ts"" uid=""{$uid}"">")
    [void]$sb2.AppendLine("    <Properties action=""U"" thisDrive=""SHOW"" allDrives=""NOCHANGE"" userName="""" path=""$($d.Share)"" label=""$($d.Label)"" persistent=""1"" useLetter=""1"" letter=""$($d.Letter)"">")
    [void]$sb2.AppendLine("      <Filters>")
    if ($d.FType -eq 'Group') {
        [void]$sb2.AppendLine("        <FilterGroup bool=""AND"" not=""0"" name=""$($d.FVal)"" sid="""" userContext=""1"" primaryGroup=""0"" localGroup=""0""/>")
    } else {
        [void]$sb2.AppendLine("        <FilterOrgUnit bool=""AND"" not=""0"" name=""LDAP://$($d.FVal)"" userContext=""1"" directMember=""0""/>")
    }
    [void]$sb2.AppendLine("      </Filters>")
    [void]$sb2.AppendLine("    </Properties>")
    [void]$sb2.AppendLine("  </Drive>")
}
[void]$sb2.AppendLine("</Drives>")
[System.IO.File]::WriteAllText("$dDir\Drives.xml", $sb2.ToString(), [System.Text.Encoding]::UTF8)
Write-Output "  [OK] Drives.xml written (M: S: T: K: R: with group/OU ILT)"

$iniPath = "$gpoPath\GPT.INI"
$raw = [System.IO.File]::ReadAllText($iniPath)
$ver = 0; if ($raw -match '(?m)^Version=(\d+)') { $ver = [int]$Matches[1] }
$uVer = (($ver -shr 16) -band 0xFFFF) + 1
$mVer = $ver -band 0xFFFF
$newVer = ($uVer -shl 16) -bor $mVer
$machExt = ''; if ($raw -match '(?m)^gPCMachineExtensionNames=([^\r\n]+)') { $machExt = $Matches[1] }
$ini = "[General]`r`nVersion=$newVer`r`n"
if ($machExt) { $ini += "gPCMachineExtensionNames=$machExt`r`n" }
$ini += "gPCUserExtensionNames=[{5794DAFD-BE60-433f-88A2-1A31939AC01F}{D02B1F72-3407-48AE-BA88-E8213C6761F1}]`r`n"
[System.IO.File]::WriteAllText($iniPath, $ini, [System.Text.Encoding]::ASCII)
Write-Output "  [OK] GPT.INI updated"

Write-Output ""
Write-Output "=== All CSC GPOs ==="
Get-GPO -All -Domain $domain | Where-Object { $_.DisplayName -like 'CSC - *' } |
    Select-Object DisplayName, GpoStatus | Sort-Object DisplayName | Format-Table -AutoSize
