# ================================
# Windows 主机名 / IP 配置脚本
# 使用方法：
# 1. 先修改下面的配置区
# 2. 用管理员权限运行 PowerShell
# 3. 执行本脚本
# 4. 执行完成后重启系统
# ================================

# ===== 配置区开始 =====
$NewComputerName = "win10-ltsc-192-168-11-162"
$IPAddress       = "192.168.11.162"
$PrefixLength    = 24
$Gateway         = "192.168.11.1"
$DnsServers      = @("192.168.34.40","223.5.5.5")
# 如需指定网卡名，可填写，例如 "以太网"
# 留空则自动选择当前状态为 Up 的第一块物理/虚拟以太网卡
$PreferredAdapterName = ""
# ===== 配置区结束 =====

$ErrorActionPreference = "Stop"

function Write-Info($msg) {
    Write-Host "[INFO] $msg" -ForegroundColor Cyan
}

function Write-Ok($msg) {
    Write-Host "[ OK ] $msg" -ForegroundColor Green
}

function Write-WarnMsg($msg) {
    Write-Host "[WARN] $msg" -ForegroundColor Yellow
}

function Write-Fail($msg) {
    Write-Host "[FAIL] $msg" -ForegroundColor Red
}

try {
    Write-Info "开始执行主机名与网络配置"

    # 1. 检查管理员权限
    $currentIdentity = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = New-Object Security.Principal.WindowsPrincipal($currentIdentity)
    $isAdmin = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
    if (-not $isAdmin) {
        throw "请使用管理员权限运行 PowerShell"
    }
    Write-Ok "管理员权限检查通过"

    # 2. 校验 IP
    [void][System.Net.IPAddress]::Parse($IPAddress)
    [void][System.Net.IPAddress]::Parse($Gateway)
    foreach ($dns in $DnsServers) {
        [void][System.Net.IPAddress]::Parse($dns)
    }
    if ($PrefixLength -lt 0 -or $PrefixLength -gt 32) {
        throw "PrefixLength 必须在 0 到 32 之间"
    }
    Write-Ok "IP 参数校验通过"

    # 3. 选择网卡
    if ($PreferredAdapterName -and $PreferredAdapterName.Trim() -ne "") {
        $nic = Get-NetAdapter -Name $PreferredAdapterName -ErrorAction Stop
    }
    else {
        $nic = Get-NetAdapter |
                Where-Object {
                    $_.Status -eq "Up" -and
                            $_.InterfaceDescription -notmatch "Bluetooth|Wireless|Wi-Fi|VPN" -and
                            $_.Name -notmatch "Bluetooth|无线|Wi-Fi|VPN"
                } |
                Sort-Object InterfaceMetric, ifIndex |
                Select-Object -First 1
    }

    if (-not $nic) {
        throw "未找到可用网卡，请手工指定 `$PreferredAdapterName"
    }

    Write-Info "选中的网卡: Name=$($nic.Name), ifIndex=$($nic.ifIndex), Status=$($nic.Status)"
    Write-Ok "网卡选择完成"

    # 4. 删除旧 IPv4 地址
    $oldIPs = Get-NetIPAddress -InterfaceIndex $nic.ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue |
            Where-Object { $_.IPAddress -ne "127.0.0.1" }

    foreach ($item in $oldIPs) {
        Write-Info "删除旧 IP: $($item.IPAddress)"
        Remove-NetIPAddress `
            -InterfaceIndex $nic.ifIndex `
            -IPAddress $item.IPAddress `
            -Confirm:$false `
            -ErrorAction SilentlyContinue
    }

    # 5. 删除旧默认路由
    $oldRoutes = Get-NetRoute -InterfaceIndex $nic.ifIndex -AddressFamily IPv4 -DestinationPrefix "0.0.0.0/0" -ErrorAction SilentlyContinue
    foreach ($route in $oldRoutes) {
        Write-Info "删除旧默认路由: NextHop=$($route.NextHop)"
        Remove-NetRoute `
            -InterfaceIndex $nic.ifIndex `
            -DestinationPrefix "0.0.0.0/0" `
            -NextHop $route.NextHop `
            -Confirm:$false `
            -ErrorAction SilentlyContinue
    }

    Write-Ok "旧 IP 和默认路由清理完成"

    # 6. 配置新 IP / 网关
    Write-Info "写入新 IP: $IPAddress/$PrefixLength, Gateway=$Gateway"
    New-NetIPAddress `
        -InterfaceIndex $nic.ifIndex `
        -IPAddress $IPAddress `
        -PrefixLength $PrefixLength `
        -DefaultGateway $Gateway `
        -AddressFamily IPv4 `
        -ErrorAction Stop | Out-Null

    Write-Ok "静态 IP 配置完成"

    # 7. 配置 DNS
    Write-Info "写入 DNS: $($DnsServers -join ', ')"
    Set-DnsClientServerAddress `
        -InterfaceIndex $nic.ifIndex `
        -ServerAddresses $DnsServers `
        -ErrorAction Stop

    Write-Ok "DNS 配置完成"

    # 8. 修改主机名
    if ($env:COMPUTERNAME -ne $NewComputerName) {
        Write-Info "当前主机名: $env:COMPUTERNAME"
        Write-Info "目标主机名: $NewComputerName"
        Rename-Computer -NewName $NewComputerName -Force -ErrorAction Stop
        Write-Ok "主机名修改完成，重启后生效"
    }
    else {
        Write-WarnMsg "主机名已经是目标值，无需修改"
    }

    Write-Host ""
    Write-Ok "全部配置已完成"

    # 新增：直接执行重启
    Write-Host "系统将在 5 秒后自动重启..." -ForegroundColor Yellow
    Start-Sleep -Seconds 5
    Restart-Computer -Force
}
catch {
    Write-Fail $_.Exception.Message
    exit 1
}