# Apply China Docker Hub registry mirrors to Docker Desktop daemon.json.
# Safe merge: keeps existing keys; only sets/extends registry-mirrors.
# Compatible with Windows PowerShell 5.1.
param(
    [switch]$NoRestartHint
)

$ErrorActionPreference = "Stop"
$Root = Split-Path -Parent $PSScriptRoot

$dockerDir = Join-Path $env:USERPROFILE ".docker"
New-Item -ItemType Directory -Force -Path $dockerDir | Out-Null
$daemonPath = Join-Path $dockerDir "daemon.json"

$wanted = @(
    "https://docker.m.daocloud.io",
    "https://docker.1ms.run",
    "https://docker.xuanyuan.me"
)

$cfg = [ordered]@{}
if (Test-Path -LiteralPath $daemonPath) {
    try {
        $raw = Get-Content -LiteralPath $daemonPath -Raw -Encoding UTF8
        if ($raw -and $raw.Trim()) {
            $obj = $raw | ConvertFrom-Json
            foreach ($p in $obj.PSObject.Properties) {
                $cfg[$p.Name] = $p.Value
            }
        }
    } catch {
        Write-Host "  !!  existing daemon.json parse failed; rewriting mirrors" -ForegroundColor Yellow
        $cfg = [ordered]@{}
    }
}

$existing = @()
if ($cfg.Contains("registry-mirrors") -and $cfg["registry-mirrors"]) {
    $existing = @($cfg["registry-mirrors"] | ForEach-Object { [string]$_ })
}
$merged = New-Object System.Collections.Generic.List[string]
foreach ($m in ($wanted + $existing)) {
    if ($m -and -not $merged.Contains($m)) { [void]$merged.Add($m) }
}
$cfg["registry-mirrors"] = @($merged)

$json = $cfg | ConvertTo-Json -Depth 8
Set-Content -LiteralPath $daemonPath -Value $json -Encoding UTF8
Write-Host ("  OK  Docker mirrors -> {0}" -f $daemonPath) -ForegroundColor DarkGray
foreach ($m in $merged) {
    Write-Host ("       {0}" -f $m) -ForegroundColor DarkGray
}

if (-not $NoRestartHint) {
    Write-Host "  !!  Restart Docker Desktop once if compose still cannot pull" -ForegroundColor Yellow
}
