# HS Data Collector - Desinstalador
# Requer privilégios de administrador

param(
    [string]$InstallPath = "C:\Program Files\HS Data Collector"
)

# Verificar privilégios de administrador
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
if (-not $isAdmin) {
    Write-Host "Erro: Este desinstalador requer privilégios de administrador!"
    Read-Host "Pressione ENTER para sair"
    exit 1
}

Clear-Host
Write-Host "HS Data Collector - Desinstalador"
Write-Host "===================================="
Write-Host ""

# Confirmação
Write-Host "Atencao: Esta acao removerah completamente o HS Data Collector" -ForegroundColor Yellow
Write-Host ""
$confirm = Read-Host "Tem certeza que deseja desinstalar? (S/N)"
if ($confirm -ne "S" -and $confirm -ne "s") {
    Write-Host "Desinstalacao cancelada."
    exit 0
}

Write-Host ""
Write-Host "Desinstalando..."

$serviceName = "HsDataCollector"

# Parar serviço
$service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue

if ($service) {
    try {
        Stop-Service -Name $serviceName -Force -ErrorAction Stop
        Write-Host "Servico parado" -ForegroundColor Green
    }
    catch {
        Write-Host "Erro ao parar o servico: $_" -ForegroundColor Red
    }
    
    Start-Sleep -Seconds 2
    
    # Remover serviço usando sc.exe (mais confiável)
    try {
        sc.exe delete $serviceName | Out-Null
        Write-Host "Windows Service removido" -ForegroundColor Green
    }
    catch {
        Write-Host "Erro ao remover o servico: $_" -ForegroundColor Red
    }
}
else {
    Write-Host "Servico nao encontrado" -ForegroundColor Yellow
}

# Remover pasta de instalação
if (Test-Path $InstallPath) {
    try {
        Remove-Item -Path $InstallPath -Recurse -Force -ErrorAction Stop
        Write-Host "Pasta de instalacao removida" -ForegroundColor Green
    }
    catch {
        Write-Host "Erro ao remover pasta: $_" -ForegroundColor Red
        Write-Host "Voce pode remover manualmente em: $InstallPath" -ForegroundColor Yellow
    }
}
else {
    Write-Host "Pasta de instalacao nao encontrada" -ForegroundColor Yellow
}

Write-Host ""
Write-Host "Desinstalacao concluida!" -ForegroundColor Green
Write-Host ""

Write-Host "Pressione ENTER para fechar" -ForegroundColor Yellow
Read-Host "Aguardando ... "
