[CmdletBinding()]
param(
    [Parameter(Mandatory)][ValidatePattern('^[a-z0-9]{3,24}$')][string]$StorageAccountName,
    [Parameter(Mandatory)][ValidatePattern('^[a-z0-9-]{3,63}$')][string]$ShareName,
    [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$StorageKey
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

$fileHost = "$StorageAccountName.file.core.windows.net"
$profilePath = "\\$fileHost\$ShareName"
$programRoot = 'C:\ProgramData\AvdWorkshop'
$markerScriptPath = Join-Path $programRoot 'Write-FSLogixProfileMarker.ps1'

if (-not (Test-Path -LiteralPath $programRoot)) {
    New-Item -ItemType Directory -Path $programRoot -Force | Out-Null
}

$markerScript = @'
[CmdletBinding()]
param()

$ErrorActionPreference = 'Stop'
$markerDirectory = Join-Path $env:APPDATA 'AzureWorkshopz'
$markerPath = Join-Path $markerDirectory 'fslogix-profile-marker.json'
if (-not (Test-Path -LiteralPath $markerDirectory)) {
    New-Item -ItemType Directory -Path $markerDirectory -Force | Out-Null
}

$existing = $null
if (Test-Path -LiteralPath $markerPath) {
    try { $existing = Get-Content -LiteralPath $markerPath -Raw | ConvertFrom-Json } catch { $existing = $null }
}
$proof = [ordered]@{
    Marker = 'ProfileMarkerPresent'
    FirstHost = if ($existing -and $existing.FirstHost) { [string]$existing.FirstHost } else { [string]$env:COMPUTERNAME }
    CurrentHost = [string]$env:COMPUTERNAME
    FirstSeenUtc = if ($existing -and $existing.FirstSeenUtc) { [string]$existing.FirstSeenUtc } else { [DateTime]::UtcNow.ToString('o') }
    LastSeenUtc = [DateTime]::UtcNow.ToString('o')
}
[System.IO.File]::WriteAllText($markerPath, ($proof | ConvertTo-Json), [System.Text.UTF8Encoding]::new($false))

if (-not [System.Diagnostics.EventLog]::SourceExists('AVDWorkshop')) {
    New-EventLog -LogName Application -Source 'AVDWorkshop'
}
$message = "FSLogix profile marker observed. FirstHost=$($proof.FirstHost); CurrentHost=$($proof.CurrentHost); Marker=$($proof.Marker)"
Write-EventLog -LogName Application -Source 'AVDWorkshop' -EventId 41080 -EntryType Information -Message $message
'@
[System.IO.File]::WriteAllText($markerScriptPath, $markerScript, [System.Text.UTF8Encoding]::new($false))
if (-not [System.Diagnostics.EventLog]::SourceExists('AVDWorkshop')) {
    New-EventLog -LogName Application -Source 'AVDWorkshop'
}

$kerberosPath = 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\Kerberos\Parameters'
$azureAdPolicyPath = 'HKLM:\SOFTWARE\Policies\Microsoft\AzureADAccount'
$fslogixPath = 'HKLM:\SOFTWARE\FSLogix\Profiles'
foreach ($path in @($kerberosPath, $azureAdPolicyPath, $fslogixPath)) {
    if (-not (Test-Path -LiteralPath $path)) { New-Item -Path $path -Force | Out-Null }
}

New-ItemProperty -Path $kerberosPath -Name 'CloudKerberosTicketRetrievalEnabled' -PropertyType DWord -Value 1 -Force | Out-Null
New-ItemProperty -Path $azureAdPolicyPath -Name 'LoadCredKeyFromProfile' -PropertyType DWord -Value 1 -Force | Out-Null
New-ItemProperty -Path $fslogixPath -Name 'Enabled' -PropertyType DWord -Value 1 -Force | Out-Null
New-ItemProperty -Path $fslogixPath -Name 'VHDLocations' -PropertyType MultiString -Value @($profilePath) -Force | Out-Null
New-ItemProperty -Path $fslogixPath -Name 'VolumeType' -PropertyType String -Value 'VHDX' -Force | Out-Null
New-ItemProperty -Path $fslogixPath -Name 'IsDynamic' -PropertyType DWord -Value 1 -Force | Out-Null
New-ItemProperty -Path $fslogixPath -Name 'DeleteLocalProfileWhenVHDShouldApply' -PropertyType DWord -Value 1 -Force | Out-Null
New-ItemProperty -Path $fslogixPath -Name 'FlipFlopProfileDirectoryName' -PropertyType DWord -Value 1 -Force | Out-Null
New-ItemProperty -Path $fslogixPath -Name 'LockedRetryCount' -PropertyType DWord -Value 12 -Force | Out-Null
New-ItemProperty -Path $fslogixPath -Name 'LockedRetryInterval' -PropertyType DWord -Value 5 -Force | Out-Null
New-ItemProperty -Path $fslogixPath -Name 'ReAttachIntervalSeconds' -PropertyType DWord -Value 15 -Force | Out-Null
New-ItemProperty -Path $fslogixPath -Name 'ReAttachRetryCount' -PropertyType DWord -Value 3 -Force | Out-Null
New-ItemProperty -Path $fslogixPath -Name 'SizeInMBs' -PropertyType DWord -Value 30000 -Force | Out-Null

$runPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'
New-ItemProperty -Path $runPath -Name 'AVDWorkshopProfileMarker' -PropertyType String -Value "powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"$markerScriptPath`"" -Force | Out-Null

$winHttpService = Get-Service -Name 'WinHttpAutoProxySvc' -ErrorAction Stop
if ($winHttpService.Status -ne 'Running') {
    & sc.exe start WinHttpAutoProxySvc | Out-Null
}
$ipHelperService = Get-Service -Name 'iphlpsvc' -ErrorAction Stop
if ($ipHelperService.Status -ne 'Running') {
    Start-Service -Name 'iphlpsvc'
}

$dns = Resolve-DnsName -Name $fileHost -Type A -ErrorAction Stop
$tcp = Test-NetConnection -ComputerName $fileHost -Port 445 -WarningAction SilentlyContinue
if (-not $tcp.TcpTestSucceeded) { throw "TCP 445 to the private Azure Files endpoint failed." }

try {
    & cmdkey.exe "/add:$fileHost" "/user:localhost\$StorageAccountName" "/pass:$StorageKey" | Out-Null
    if (-not (Test-Path -LiteralPath $profilePath)) { throw 'The authenticated Azure Files UNC path could not be opened.' }
    & icacls.exe $profilePath '/inheritance:r' | Out-Null
    & icacls.exe $profilePath '/grant:r' 'CREATOR OWNER:(OI)(CI)(IO)(F)' 'Authenticated Users:(RX,WD,AD)' 'SYSTEM:(OI)(CI)(F)' 'BUILTIN\Administrators:(OI)(CI)(F)' | Out-Null
    if ($LASTEXITCODE -ne 0) { throw "icacls failed with exit code $LASTEXITCODE." }
}
finally {
    & cmdkey.exe "/delete:$fileHost" | Out-Null
}

$fslogixVersion = $null
$fslogixService = Get-CimInstance Win32_Service -Filter "Name='frxsvc'" -ErrorAction SilentlyContinue
$fslogixExecutable = 'C:\Program Files\FSLogix\Apps\frxsvc.exe'
if (Test-Path -LiteralPath $fslogixExecutable) {
    $fslogixVersion = (Get-Item -LiteralPath $fslogixExecutable).VersionInfo.FileVersion
}

[pscustomobject]@{
    ConfigurationStatus = 'Applied'
    ComputerName = [string]$env:COMPUTERNAME
    PrivateDnsResolved = (@($dns).Count -gt 0)
    SmbPort445Reachable = [bool]$tcp.TcpTestSucceeded
    EntraKerberosClientEnabled = ((Get-ItemPropertyValue -Path $kerberosPath -Name 'CloudKerberosTicketRetrievalEnabled') -eq 1)
    LoadCredentialKeyFromProfile = ((Get-ItemPropertyValue -Path $azureAdPolicyPath -Name 'LoadCredKeyFromProfile') -eq 1)
    FslogixEnabled = ((Get-ItemPropertyValue -Path $fslogixPath -Name 'Enabled') -eq 1)
    VhdType = 'VHDX'
    DynamicVhd = $true
    DeleteLocalProfile = $true
    FslogixServicePresent = [bool]$fslogixService
    FslogixVersionDetected = [bool]$fslogixVersion
    CreatorOwnerAclApplied = $true
    ProfileMarkerLogonScriptInstalled = (Test-Path -LiteralPath $markerScriptPath)
} | ConvertTo-Json -Compress
