param(
    [string]$InstallDirectory = (Split-Path -Path $PSScriptRoot -Parent)
)

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

$expectedExe = Join-Path $InstallDirectory "agent\IAUWP.Agent.exe"
$pidPath = Join-Path $InstallDirectory "run\agent.pid"

function Get-AgentProcessPath {
    param($Process)
    try {
        return $Process.MainModule.FileName
    }
    catch {
        return $null
    }
}

$stoppedPids = @()

# The PID file is a hint (the agent writes its own pid at startup). Prefer it,
# but never stop a process whose executable is not this install's agent.
if (Test-Path -Path $pidPath) {
    $pidText = Get-Content -Path $pidPath -Raw
    if ($pidText -match '^\s*\d+\s*$') {
        $agentPid = [int]$pidText
        $process = Get-Process -Id $agentPid -ErrorAction SilentlyContinue
        if ($process) {
            $actualExe = Get-AgentProcessPath -Process $process
            if ($actualExe -and -not [string]::Equals($actualExe, $expectedExe, [StringComparison]::OrdinalIgnoreCase)) {
                Write-Host "PID $agentPid points at '$actualExe', not this install's agent. Treating the PID file as stale."
            }
            else {
                Stop-Process -Id $agentPid
                Wait-Process -Id $agentPid -Timeout 15 -ErrorAction SilentlyContinue
                $stoppedPids += $agentPid
            }
        }
    }
}

# Fallback for a missing or stale PID file: stop any IAUWP.Agent process that
# is actually running from this install's agent executable.
$pathMatchedProcesses = @(Get-Process -Name "IAUWP.Agent" -ErrorAction SilentlyContinue | Where-Object {
    $candidateExe = Get-AgentProcessPath -Process $_
    $candidateExe -and [string]::Equals($candidateExe, $expectedExe, [StringComparison]::OrdinalIgnoreCase)
})
foreach ($process in $pathMatchedProcesses) {
    if ($stoppedPids -contains $process.Id) {
        continue
    }
    Stop-Process -Id $process.Id
    Wait-Process -Id $process.Id -Timeout 15 -ErrorAction SilentlyContinue
    $stoppedPids += $process.Id
}

if (Test-Path -Path $pidPath) {
    Remove-Item -Path $pidPath -Force
}

if ($stoppedPids.Count -gt 0) {
    Write-Host "ImageAnywhere Agent stopped (PID $($stoppedPids -join ', '))."
}
else {
    Write-Host "No running ImageAnywhere Agent process was found for this install. Nothing to stop."
}
