@echo off
setlocal
set "BDIR=%~dp0"
echo.
echo === Portal Union: Code aktualisieren ===
echo.
powershell -NoProfile -ExecutionPolicy Bypass -Command "$m='### PS'+'CODE ###';$me=[IO.File]::ReadAllText('%~f0');$p=$me.IndexOf($m);$nl=$me.IndexOf([char]10,$p);Invoke-Expression $me.Substring($nl+1)"
echo.
pause
exit /b
### PSCODE ###
$ErrorActionPreference = 'Stop'
$here = $env:BDIR
$root = Split-Path -Parent ($here.TrimEnd('\'))
if (-not (Test-Path -LiteralPath (Join-Path $root 'index.html'))) {
  Write-Host ('FEHLER: ' + $root + ' ist nicht die Portal-Wurzel.') -ForegroundColor Red; return
}
Write-Host ('Ziel: ' + $root)
$bundles = Get-ChildItem -LiteralPath $here -Filter 'sync-bundle-*.txt' | Sort-Object Name
if (-not $bundles) { Write-Host 'FEHLER: keine sync-bundle-*.txt gefunden.' -ForegroundColor Red; return }
$flush = {
  param($d, $rel, $expLen, $b64)
  if (-not $rel) { return $null }
  $bytes = [Convert]::FromBase64String($b64)
  $full = Join-Path $d ($rel -replace '/', '\')
  $pd = Split-Path -Parent $full
  if (-not (Test-Path -LiteralPath $pd)) { New-Item -ItemType Directory -Path $pd -Force | Out-Null }
  [IO.File]::WriteAllBytes($full, $bytes)
  return ($bytes.Length -eq $expLen)
}
$ok = 0; $bad = 0; $rel = $null; $expLen = 0; $sb = New-Object System.Text.StringBuilder
foreach ($b in $bundles) {
  Write-Host ('-> ' + $b.Name)
  foreach ($line in [IO.File]::ReadAllLines($b.FullName)) {
    if ($line.StartsWith('### FILE: ')) {
      $r = & $flush $root $rel $expLen $sb.ToString()
      if ($r -eq $true) { $ok++ } elseif ($r -eq $false) { $bad++ }
      $meta = $line.Substring(10); $k = $meta.LastIndexOf(' | ')
      $rel = $meta.Substring(0, $k); $expLen = [int]$meta.Substring($k + 3); $sb = New-Object System.Text.StringBuilder
    } elseif ($line.StartsWith('###')) { continue }
    elseif ($line.Length -gt 0) { [void]$sb.Append($line) }
  }
}
$r = & $flush $root $rel $expLen $sb.ToString()
if ($r -eq $true) { $ok++ } elseif ($r -eq $false) { $bad++ }
Write-Host ''
if ($bad -eq 0) { Write-Host ('FERTIG: ' + $ok + ' Dateien.') -ForegroundColor Green }
else { Write-Host ('FERTIG: ' + $ok + ' ok, ' + $bad + ' Fehler.') -ForegroundColor Yellow }
