#!/usr/bin/pwsh

param(
    [Alias('h')][switch]$SHOW_HELP,
    [Alias('m')][string]$HOME_DIR=""
)

if ($SHOW_HELP) {
    Write-Host "DESCRIPTION: Install Anypoint Monitoring OpenTelemetry Collector"
    Write-Host "Usage: .\$($MyInvocation.MyCommand) [options]"
    Write-Host " "
    Write-Host "Options:"
    Write-Host "-h,       Show help"
    Write-Host "-m [DIR]  Set home directory - defaults to MULE_HOME"
    Write-Host " "
    exit 0
}

# Determine the home directory
if (-not $HomeDir -or -not (Test-Path -Path $HomeDir -PathType Container)) {
    if ($env:MULE_HOME -and (Test-Path -Path $env:MULE_HOME -PathType Container)) {
        $HomeDir = $env:MULE_HOME
    } else {
        $scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
        $HomeDir = Resolve-Path -Path (Join-Path -Path $scriptDir -ChildPath "..\..")
    }
    # Source the serviceHelper.ps1
    . (Join-Path -Path $HomeDir -ChildPath "am\bin\tools\serviceHelper.ps1")
}

Log-Info "MULE_HOME is set to $HomeDir"

# Set AM_HOME based on the determined HomeDir
$AM_HOME = Join-Path -Path $HomeDir -ChildPath "am"

Log-Info "AM_HOME is set to $AM_HOME"

$amScript = Join-Path -Path $AM_HOME -ChildPath "bin\am.ps1"
if (Test-Path $amScript) {

    try {
        # Stop the DirectoryWatcher
        Log-Info "Attempting to stop DirectoryWatcher..."
        $targetClass = "com.mulesoft.dias.mule.agent.DirectoryWatcher"
        # Get all java.exe processes with full command lines
        $javaProcesses = Get-CimInstance Win32_Process | Where-Object {
            $_.Name -eq "java.exe" -and $_.CommandLine -match [regex]::Escape($targetClass)
        }

        $className = $targetClass.Split('.')[-1]

        if ($javaProcesses.Count -eq 0) {
            Log-Info "No running Java process found for class $className."
        }

        foreach ($proc in $javaProcesses) {
            Log-Info "Stopping Java process with PID $($proc.ProcessId) running class $className..."
            Stop-Process -Id $proc.ProcessId -Force
        }

        Log-Info "Stopping Anypoint Monitoring OpenTelemetry Collector."
        Start-Process -FilePath "powershell.exe" -ArgumentList "-File `"$amScript`" stop" -NoNewWindow -Wait
        Log-Info "Anypoint Monitoring OpenTelemetry Collector stopped."
        # Remove directories and files
        Log-Info "Removing configuration files and directories..."
        Remove-Item -Path (Join-Path -Path $AM_HOME -ChildPath "config\prospectors") -Recurse -Force -ErrorAction SilentlyContinue
        Remove-Item -Path (Join-Path -Path $AM_HOME -ChildPath "config\certs") -Recurse -Force -ErrorAction SilentlyContinue
        Remove-Item -Path (Join-Path -Path $AM_HOME -ChildPath "config\proxy.url") -Force -ErrorAction SilentlyContinue
        Remove-Item -Path (Join-Path -Path $AM_HOME -ChildPath "install.mode") -Force -ErrorAction SilentlyContinue
        Remove-Item -Path (Join-Path -Path $env:AM_HOME -ChildPath "directorywatcher.pid") -Force -ErrorAction SilentlyContinue

        # Remove specific JAR files
        $jarPaths = @(
            "$HomeDir\server-plugins\mule-agent-plugin\lib\mule-agent-dias-*.jar",
            "$HomeDir\server-plugins\mule-agent-plugin\lib\analytics-metrics-collector-*.jar",
            "$HomeDir\server-plugins\mule-agent-plugin\lib\modules\mule-agent-dias-*.jar",
            "$HomeDir\server-plugins\mule-agent-plugin\lib\modules\analytics-metrics-collector-*.jar",
            "$HomeDir\plugins\mule-agent-plugin\lib\modules\mule-agent-dias-*.jar",
            "$HomeDir\plugins\mule-agent-plugin\lib\modules\analytics-metrics-collector-*.jar"
        )

        foreach ($jarPath in $jarPaths) {
            Remove-Item -Path $jarPath -Force -ErrorAction SilentlyContinue
        }

        Log-Info "Anypoint Monitoring uninstallation completed successfully"
        exit 0
    } catch {

    }
} else {
    Log-Info "Warning: am.ps1 not found at: $amScript"
    Log-Info "Anypoint Monitoring uninstallation failed"
    exit 1
}