# refresh_proxy_dns.ps1
# 刷新 Windows DNS + Edge 进程缓存 + 重启 Clash Verge

Write-Host "=== 开始刷新 DNS / 浏览器 / 代理缓存 ===" -ForegroundColor Cyan


# 1. 关闭 Edge
Write-Host "`n[1/5] 正在关闭 Edge / WebView2..." -ForegroundColor Yellow

$edgeProcesses = @(
    "msedge",
    "msedgewebview2"
)

foreach ($proc in $edgeProcesses) {
    Get-Process -Name $proc -ErrorAction SilentlyContinue |
            Stop-Process -Force -ErrorAction SilentlyContinue
}

Start-Sleep -Seconds 2

Write-Host "Edge / WebView2 已关闭。" -ForegroundColor Green


# 2. 清 Windows DNS 缓存
Write-Host "`n[2/5] 正在清理 Windows DNS 缓存..." -ForegroundColor Yellow

ipconfig /flushdns | Out-Null
Clear-DnsClientCache -ErrorAction SilentlyContinue

Write-Host "Windows DNS 缓存已清理。" -ForegroundColor Green


# 3. 关闭 Clash Verge / mihomo
Write-Host "`n[3/5] 正在关闭 Clash Verge / mihomo..." -ForegroundColor Yellow

$clashProcesses = @(
    "Clash Verge",
    "clash-verge",
    "clash-verge-service",
    "mihomo",
    "clash",
    "verge-mihomo"
)

foreach ($proc in $clashProcesses) {
    Get-Process -Name $proc -ErrorAction SilentlyContinue |
            Stop-Process -Force -ErrorAction SilentlyContinue
}

Start-Sleep -Seconds 2

Write-Host "Clash Verge / mihomo 相关进程已尝试关闭。" -ForegroundColor Green


# 4. 重新启动 Clash Verge
Write-Host "`n[4/5] 正在重新启动 Clash Verge..." -ForegroundColor Yellow

$clashVergeDir = "C:\Program Files\Clash Verge"

$possibleExe = @(
    "Clash Verge.exe",
    "clash-verge.exe",
    "Clash Verge Rev.exe",
    "clash-verge-rev.exe"
)

$clashExe = $null

foreach ($exe in $possibleExe) {
    $path = Join-Path $clashVergeDir $exe

    if (Test-Path $path) {
        $clashExe = $path
        break
    }
}

if ($clashExe) {
    Start-Process $clashExe
    Write-Host "已启动：$clashExe" -ForegroundColor Green
} else {
    Write-Host "未找到 Clash Verge 可执行文件，请检查目录：" -ForegroundColor Red
    Write-Host $clashVergeDir -ForegroundColor Red
}

Start-Sleep -Seconds 5


# 5. 重新打开 Edge
Write-Host "`n[5/5] 正在重新打开 Edge..." -ForegroundColor Yellow

$edgeExe = "${env:ProgramFiles(x86)}\Microsoft\Edge\Application\msedge.exe"

if (-not (Test-Path $edgeExe)) {
    $edgeExe = "$env:ProgramFiles\Microsoft\Edge\Application\msedge.exe"
}

if (Test-Path $edgeExe) {
    Start-Process $edgeExe
    Write-Host "Edge 已启动。" -ForegroundColor Green
} else {
    Start-Process "msedge.exe"
    Write-Host "已尝试通过 PATH 启动 Edge。" -ForegroundColor Green
}


Write-Host "`n=== 刷新完成 ===" -ForegroundColor Cyan
Write-Host "如果 Clash Verge 还在初始化代理内核，等几秒后再访问网站测试。" -ForegroundColor Cyan