# Percepta SIEM Agent installer
$Dir = Split-Path -Parent $MyInvocation.MyCommand.Path
$AgentName = 'percepta-agent.exe'
$AgentSource = Join-Path $Dir $AgentName
$ServiceName = 'PerceptaSIEMAgent'
$LogHint = Join-Path $env:ProgramData 'percepta_agent\logs\gui-startup.log'
$IsAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-Not (Test-Path $AgentSource)) { throw "Agent executable not found: $AgentSource" }
if ($IsAdmin) {
  $InstallDir = Join-Path $env:ProgramFiles 'Percepta SIEM Agent'
  New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null
  foreach ($Name in @('percepta-agent.exe', 'server-config.txt', 'ca_cert.pem', 'otk.txt')) {
    $Source = Join-Path $Dir $Name
    if (Test-Path $Source) {
      Copy-Item -Force $Source (Join-Path $InstallDir $Name)
    }
  }
  $AgentExe = Join-Path $InstallDir $AgentName
  $BinPath = '"' + $AgentExe + '" --service'
  $ServiceQuery = sc.exe query $ServiceName 2>$null | Out-String
  if ($LASTEXITCODE -eq 0 -and $ServiceQuery -match 'SERVICE_NAME') {
    sc.exe stop $ServiceName 2>$null | Out-Null
    Start-Sleep -Seconds 1
    sc.exe config $ServiceName binPath= $BinPath start= auto | Out-Null
  } else {
    sc.exe create $ServiceName binPath= $BinPath start= auto DisplayName= 'Percepta SIEM Agent' | Out-Null
  }
  sc.exe start $ServiceName | Out-Null
  Write-Host 'Percepta agent service installed and started.'
} else {
  $AgentExe = $AgentSource
  Write-Host 'Administrator rights not detected. Launching the GUI only.'
  Write-Host 'Re-run this script as Administrator if you want the Windows service installed.'
}
try {
  $Proc = Start-Process -FilePath $AgentExe -WorkingDirectory (Split-Path -Parent $AgentExe) -PassThru
  Start-Sleep -Seconds 3
  if ($Proc.HasExited) {
    Write-Warning ('Percepta agent exited immediately with code ' + $Proc.ExitCode + '. Check ' + $LogHint)
  } else {
    Write-Host ('Percepta agent GUI launched from ' + (Split-Path -Parent $AgentExe))
  }
} catch {
  Write-Error ('Failed to launch Percepta agent GUI. Check ' + $LogHint + ' and Windows Event Viewer. ' + $_.Exception.Message)
  throw
}
