$ErrorActionPreference = 'Stop'
$principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Start-Process powershell.exe -Verb RunAs -ArgumentList '-NoProfile','-ExecutionPolicy','Bypass','-File',('"' + $MyInvocation.MyCommand.Path + '"')
    exit
}
$source = Split-Path -Parent $MyInvocation.MyCommand.Path
$exeSource = Join-Path $source 'Agente-TI-Extrema-Windows.exe'
if (-not (Test-Path -LiteralPath $exeSource)) { throw 'Executavel do agente nao encontrado no pacote.' }
$installDirectory = Join-Path $env:ProgramFiles 'Prefeitura de Extrema\Agente TI Windows'
$dataDirectory = Join-Path $env:ProgramData 'PrefeituraExtrema\AgenteTIWindows'
$taskName = 'Prefeitura de Extrema - Inventario TI Windows'
$uninstallKey = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\AgenteTIExtremaWindows'
New-Item -ItemType Directory -Path $installDirectory -Force | Out-Null
New-Item -ItemType Directory -Path $dataDirectory -Force | Out-Null
Copy-Item -LiteralPath $exeSource -Destination (Join-Path $installDirectory 'Agente-TI-Extrema-Windows.exe') -Force
Copy-Item -LiteralPath (Join-Path $source 'Desinstalar-Agente-TI.ps1') -Destination (Join-Path $installDirectory 'Desinstalar-Agente-TI.ps1') -Force
& icacls.exe $installDirectory /inheritance:r /grant:r '*S-1-5-18:(OI)(CI)F' '*S-1-5-32-544:(OI)(CI)F' '*S-1-5-32-545:(OI)(CI)RX' | Out-Null
if ($LASTEXITCODE -ne 0) { throw 'Nao foi possivel proteger a pasta do programa.' }
& icacls.exe $dataDirectory /inheritance:r /grant:r '*S-1-5-18:(OI)(CI)F' '*S-1-5-32-544:(OI)(CI)F' | Out-Null
if ($LASTEXITCODE -ne 0) { throw 'Nao foi possivel proteger a pasta de configuracao.' }
$installedExe = Join-Path $installDirectory 'Agente-TI-Extrema-Windows.exe'
$configFile = Join-Path $dataDirectory 'config.dat'
if (Test-Path -LiteralPath $configFile) {
    Write-Host 'Ativacao anterior encontrada. As credenciais serao preservadas.' -ForegroundColor Cyan
    & $installedExe sync
    if ($LASTEXITCODE -ne 0) { Write-Warning 'A sincronizacao imediata falhou, mas a tarefa automatica tentara novamente.' }
} else {
    Write-Host 'Informe os dados de ativacao fornecidos pelo painel.' -ForegroundColor Cyan
    & $installedExe activate
    if ($LASTEXITCODE -ne 0) { throw 'A ativacao nao foi concluida. A tarefa automatica nao foi criada.' }
}
$action = New-ScheduledTaskAction -Execute $installedExe -Argument 'scheduled'
$startup = New-ScheduledTaskTrigger -AtStartup
$repeat = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(2) -RepetitionInterval (New-TimeSpan -Minutes 15)
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes 10)
Register-ScheduledTask -TaskName $taskName -Action $action -Trigger @($startup,$repeat) -Settings $settings -User 'SYSTEM' -RunLevel Highest -Description 'Inventario tecnico institucional da Prefeitura de Extrema. Visivel e administrado pela equipe de TI.' -Force | Out-Null
New-Item -Path $uninstallKey -Force | Out-Null
Set-ItemProperty -Path $uninstallKey -Name DisplayName -Value 'Agente TI Extrema Windows'
Set-ItemProperty -Path $uninstallKey -Name DisplayVersion -Value '1.0.1'
Set-ItemProperty -Path $uninstallKey -Name Publisher -Value 'Prefeitura Municipal de Extrema'
Set-ItemProperty -Path $uninstallKey -Name InstallLocation -Value $installDirectory
Set-ItemProperty -Path $uninstallKey -Name UninstallString -Value "powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"$installDirectory\Desinstalar-Agente-TI.ps1`""
Set-ItemProperty -Path $uninstallKey -Name NoModify -Type DWord -Value 1
Write-Host 'Instalacao concluida. O agente aparece em Aplicativos instalados e no Agendador de Tarefas.' -ForegroundColor Green
