# CNC 采集服务 - 卸载脚本
# 脚本与CncCollector.exe放在同一目录，右键以管理员身份运行
# 用法: .\uninstall.ps1

$ErrorActionPreference = "Continue"
$serviceName = "CncCollector"
$installDir = $PSScriptRoot
$exePath = Join-Path $installDir "CncCollector.exe"

Write-Host "================================================" -ForegroundColor Cyan
Write-Host "  CNC 机床数据采集服务 - 卸载脚本 v3.0" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan

# 检查管理员权限
$isAdmin = ([Security.Principal.WindowsPrincipal] [Windows.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
    Write-Host "[错误] 请以管理员权限运行此脚本！" -ForegroundColor Red
    Write-Host "`n按回车键退出..." -ForegroundColor Gray
    Read-Host
    exit 1
}

$svc = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
if (-not $svc) {
    Write-Host "[提示] 服务未安装，无需卸载。" -ForegroundColor Yellow
    Write-Host "`n按回车键退出..." -ForegroundColor Gray
    Read-Host
    exit 0
}

# 步骤1：停止服务
if ($svc.Status -eq 'Running') {
    Write-Host "[1/3] 停止服务..." -ForegroundColor Green
    Stop-Service -Name $serviceName -Force
    $svc.WaitForStatus('Stopped', (New-TimeSpan -Seconds 30))
    Start-Sleep -Seconds 2
    Write-Host "  服务已停止" -ForegroundColor Gray
} else {
    Write-Host "[1/3] 服务当前状态: $($svc.Status)，无需停止" -ForegroundColor Gray
}

# 步骤2：卸载服务
Write-Host "[2/3] 卸载服务..." -ForegroundColor Green
$uninstalled = $false

# 优先使用程序内置 --uninstall
if (Test-Path $exePath) {
    Write-Host "  尝试使用程序内置卸载..." -ForegroundColor Gray
    try {
        & $exePath --uninstall 2>&1 | ForEach-Object { Write-Host "  $_" -ForegroundColor Gray }
        if ($LASTEXITCODE -eq 0) { $uninstalled = $true }
    } catch {
        Write-Host "  内置卸载失败，尝试 InstallUtil..." -ForegroundColor Yellow
    }
}

# 降级到 InstallUtil
if (-not $uninstalled) {
    $installUtilPath = $null
    $runtimeDir = [System.Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()
    $candidatePath = Join-Path $runtimeDir "InstallUtil.exe"
    if (Test-Path $candidatePath) { $installUtilPath = $candidatePath }
    if (-not $installUtilPath) {
        $fwPath = Join-Path $env:windir "Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe"
        if (Test-Path $fwPath) { $installUtilPath = $fwPath }
    }

    if ($installUtilPath -and (Test-Path $exePath)) {
        Write-Host "  使用 InstallUtil 卸载..." -ForegroundColor Gray
        try {
            & $installUtilPath "/u" "/LogFile=" "/LogToConsole=true" $exePath 2>&1 | ForEach-Object { Write-Host "  $_" -ForegroundColor Gray }
            $uninstalled = $true
        } catch {
            Write-Host "  InstallUtil 卸载失败" -ForegroundColor Yellow
        }
    }
}

# 最终降级到 sc.exe
if (-not $uninstalled) {
    Write-Host "  使用 sc.exe 删除服务..." -ForegroundColor Gray
    sc.exe delete $serviceName | Out-Null
    $uninstalled = $true
}

Start-Sleep -Seconds 2

# 步骤3：验证
Write-Host "[3/3] 验证卸载..." -ForegroundColor Green
$check = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
if (-not $check) {
    Write-Host "`n[成功] 服务已完全卸载。" -ForegroundColor Green

    # 询问是否清理日志目录
    $logsDir = Join-Path $installDir "logs"
    if (Test-Path $logsDir) {
        Write-Host "`n  日志目录 $logsDir 仍然存在。" -ForegroundColor Yellow
        $answer = Read-Host "  是否删除日志目录？(y/N)"
        if ($answer -eq 'y' -or $answer -eq 'Y') {
            Remove-Item -Path $logsDir -Recurse -Force
            Write-Host "  日志目录已删除。" -ForegroundColor Green
        } else {
            Write-Host "  日志目录已保留。" -ForegroundColor Gray
        }
    }
} else {
    Write-Host "[错误] 服务删除失败，可能需要重启后再试。" -ForegroundColor Red
    Write-Host "  手动删除: sc.exe delete $serviceName" -ForegroundColor Yellow
}

Write-Host "`n按回车键退出..." -ForegroundColor Gray
Read-Host
